Unit Test and Mock HttpContextAccessor

Unit Test and Mock HttpContextAccessor Mock IHttpContextAccessor

In this article, we shall see how to Unit Test and Mock IHttpContextAccessor.

If you need to access headers or any HttpContext metadata in other services or modules then HttpContextAccessor helps in reading those data easily.

Let’s use the below target method which uses HttpContextAccessor in the code.

 public class EmployeeRepository : IEmployeeRepository
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        public EmployeeRepository(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public Employee GetEmployeeByID(int employeeID)
        {
            string userName = _httpContextAccessor.HttpContext.User.Identity.Name;
            Employee employee = PerformBusinessLogic(userName);
            return employee;
        }

     }

For complete example refer to the below this article,

I am using moq a mocking library that you install from NuGet.

Install-Package Moq -Version <any versin>

Below is the test method implementation to mock IHttpContextAccessor,

Mock IHttpContextAccessor,

           
 var mockHttpContextAccessor = new Mock<IHttpContextAccessor>();

Once you have a mocked interface, you are all set to call the SetUp method for mocking up all functions or properties exposed by this interface.

Below is the example, I am mocking up the property User.Identity.Name. You can mock a similar way other properties as required.

Setup Mock data for IHttpContextAccessor,

            mockHttpContextAccessor.Setup(req => req.HttpContext.User.Identity.Name).Returns(It.IsAny<string>());

If you have other metadata like HttpRequest or HttpResponse or other custom headers, you can easily mock them using mock of interface IHttpContextAccessor.

Unit Test and Mock IHttpContextAccessor

Useful 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.