Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a .NET middleware that uses Response.OnStarting

So, I created a .net core middleware that adds a header to a response. I am not finding a way to unit test this middleware, as it uses the OnStarting callback and I can't imagine how to mock or force its execution.

Here is a sample of the middleware:

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
    context.Response.OnStarting(() =>
    {
        context.Response.Headers.Add("Name", "Value");

        return Task.CompletedTask;
    });

    await next(context);
}

As the middleware interface expects a concrete instance of HttpContext, I can't imagine a way to mock it using FakeItEasy, for example.

like image 296
renanliberato Avatar asked Jan 01 '23 09:01

renanliberato


1 Answers

You can use the example in Mock HttpContext for unit testing a .NET core MVC controller? as a guide:

using Shouldly;
using Xunit;

[Fact]
public async Task Middleware_should_add_header()
{
    // Arrange:

    HttpContext ctx = new DefaultHttpContext();

    RequestDelegate next = ( HttpContext hc ) => Task.CompletedTask;

    MyMiddleware mw = new MyMiddleware();

    // Act - Part 1: InvokeAsync set-up:

    await hw.InvokeAsync( ctx, next );

    // Assert - Part 1

    ctx.Response.Headers.TryGetValue( "Name", out String value0 ).ShouldBeFalse();
    value0.ShouldBeNull();

    // Act - Part 2

    await ctx.Response.StartAsync( default );

    // Asset - Part 2

    ctx.Response.Headers.TryGetValue( "Name", out String value1 ).ShouldBeTrue();
    value1.ShouldBe( "Value" );

}
like image 174
Dai Avatar answered Jan 13 '23 16:01

Dai