Mock and Unit Test ASP.NET Middleware Component

Mock and Unit Test Middleware ASPNET

In this article, we shall see how to Mock and Unit Test ASP.NET Core Middleware component.

As we know Middleware is a component that is used in the application pipeline to handle requests and responses which can also help perform pre and post-operation within the API pipeline.

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

Today in this article, we will cover below aspects,

Getting started

I already have a sample Middleware component as below which adds a custom header(x-thecode-buzz) to the HTTP responses.

Unit Under Test as below,

We shall be using the AAA (Arrange- Act-Assert) pattern.

Mock HTTPContext using DefaultHttpContext

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

 var httpContext = new DefaultHttpContext();

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;
            };






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;




That’s All !!

Happy Coding!

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.



2 thoughts on “Mock and Unit Test ASP.NET Middleware

Leave a Reply

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