I need to find a way to unit test this middleware.
I’m trying to unit test a .NET Core middleware that adds a header to a response. The middleware uses the
OnStarting callback and I’m having difficulty mocking or forcing its execution. Here is a sample of the middleware:
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
I need to find a way to unit test this middleware, as it expects a concrete instance of
HttpContext which makes it difficult to mock with a library like
One approach to unit test this middleware is to create a
HttpContext instance manually and pass it to the middleware. Here is an example test method using xUnit and Moq:
public async Task InvokeAsync_AddsHeaderToResponse()
var httpContext = new DefaultHttpContext();
var response = new Mock<HttpResponse>();
httpContext.Response = response.Object;
var middleware = new SampleMiddleware();
await middleware.InvokeAsync(httpContext, _ => Task.CompletedTask);
response.VerifySet(r => r.Headers.Add("Name", "Value"), Times.Once);
In this test method, we create a new
DefaultHttpContext instance and set its
Response property to a
Mock<HttpResponse> instance. We then create an instance of the middleware and call its
InvokeAsync method with the
HttpContext instance we just created.
Finally, we use Moq’s
VerifySet method to assert that the
Headers.Add method was called with the expected arguments.