Unit Test and Mock HttpContext in ASP.NET Core Controller
In this article, we shall see how to perform Unit Test and Mock HttpContext in ASP.NET Core Controller.
As we understood in the Best practices of API Controller Unit Testing “Controller” unit testing is important to make API or MVC Controller robust.
The controller is a class like any other class which has members like methods and properties etc. 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.
Accessing HTTPContext in Controller
Let’s take an example accessing HTTPContext in Controller as below,
The above code GET method uses the Request object for getting custom header values and uses Repository instance to call employee details.
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();
Set up the custom header used ‘X-Custom-Header’,
httpContext.Request.Headers["X-Custom-Header"] = "88-test-tcb";
Setup the mock HttpContext in the Controller using ControllerContext.
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 Test method,
Accessing HTTPContext using HttpContextAccessor
If accessing HTTPContext using HttpContextAccessor then Unit Test cases can be written using below way,
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.