Unit Test and Mock HttpRequest in ASP.NET Core Controller

Unit Test and Mock HttpRequest in ASPNET Core Controller

In this article, we shall see how to Unit Test and Mock HttpRequest in ASP.NET Core Controller.

As we understood in the Best practices of API Controller Unit Testing “Controller” unit testing is also important to make our API robust.

Today in this article, we will cover below aspects,

The controller is a class like any other class which has members like methods and properties etc. Hence only thing we do a bit differently in controller unit testing is that the Request and Response assertion as per API specification.

API Controller methods return HTTP responses with resource details.

We shall be using the below example to perform Unit Testing and mocking of Request objects used using the HttpContext instance.

Unit Test and Mock HttpRequest in ASPNET Core Controller setup request header in fakehttpcontext for unit testing

In the above code GET method uses the Request object for getting custom header values and uses Repository instance to call employee details.

Mock HTTP Context

Please use DefaultHttpContext object to setup mock version the HttpContext in the controller.

 var httpContext = new DefaultHttpContext();

Set Customer header for Mock

Set up the custom request header used ‘X-Custom-Header’

httpContext.Request.Headers["X-Custom-Header"] = "88-test-tcb";

Setup the mock HttpContext in the Controller,

 var mockedRepository = new Mock<IEmployeeRepository>();
            var controller = new EmployeeController(mockedRepository.Object)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = httpContext,
                }
            };

Below is ACT and ASSERT,

  //ACT 
            var result = controller.Get().Result as ObjectResult;
            var actualtResult = result.Value;
            //ASSERT
            Assert.IsType<OkObjectResult>(result);

Here below is the complete method,

Unit Test and Mock HttpRequest in ASPNET Core Controllersetup request header unit test

References:

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.



4 thoughts on “Unit Test and Mock HttpRequest in ASP.NET Core Controller

  1. Thank you very much. I was stuck on mocking the Request.Scheme and I found the answer in your article. I tried stackoverflow but I’ve had problems refactoring them. Your explanation is clear and simple. Great work.

Leave a Reply

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