Unit Test and Mock HttpContext Response OnStarting method

Mock and Unit Test HttpContext Response OnStarting method

In this article, we shall see how to Unit Test and Mock HttpContext Response OnStarting method.

With this approach you can mock and unit test any middleware components in ASP.NET Core applications.

What is OnStarting() in the middleware

HttpContext OnStarting() method helps you add delegate just before sending the response to the client invoking the original request

While you add these customizations in the form of pre or post-request or response, you may want to Unit Test these components the robust code.

Getting started

I already have a sample Middleware component that uses HttpContext OnStarting() method for adding a custom header (test-thecode-buzz) to the HTTP responses.

Below is an example code calling OnStarting method,

public async Task InvokeAsync(HttpContext httpContext)
        {
            httpContext.Response.OnStarting(() =>
            {
                httpContext.Response.Headers.Add("x-thecode-buzz", "TheCodeBuzz");
                return Task.CompletedTask;
            });
            await _next(httpContext);
        }

We shall be using AAA (Arrange- Act-Assert) pattern as we learned in our Unit Testing Naming Convention article.

Lets now see how to Unit Test and Mock HttpContext.

Step1- Mock HTTPContext using DefaultHttpContext

Please use DefaultHttpContext object to set up a mock version of the HttpContext in the controller.

 var httpContext = new DefaultHttpContext();

Step2- Mocking IHttpResponseFeature

Mocking IHttpResponseFeature can be achieved as below.

     var feature = new Mock<IHttpResponseFeature>();
            feature.Setup(option => option.HasStarted).Returns(true);

Set up the mocked IHttpResponseFeature to the given HttpContext as below,

httpContext.Features.Set<IHttpResponseFeature>(feature.Object);
 RequestDelegate next = async (HttpContext hc) =>
            {
                await Task.CompletedTask;
            };

Setting up Mock Callback for OnStarting() method,

feature.Setup(m => m.OnStarting(callback, null))

Now let’s invoke the method with mocked delegates and mocked HttpResponseFeature.

//Act
            GlobalHeaderMiddleware headerMiddleware = new GlobalHeaderMiddleware(next);
            await headerMiddleware.InvokeAsync(httpContext);
            var response = httpContext.Response;

Mock and Unit Test HttpContext Response OnStarting method

That’s All !!

Happy Coding!

References :

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



One thought on “Unit Test and Mock HttpContext Response OnStarting method

  1. I am not sure how this works. The middleware should be adding a header with the value “TheCodeBuzz”, but the test is only checking for the value of “test-1231”. The unit test is not testing that the code within the OnStarting event is doing what it should. It seems to merely be testing that the features you sent in are what was returned. Which does not seem to add any value. Am I missing something?

Leave a Reply

Your email address will not be published. Required fields are marked *