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.
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" );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With