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.



11 thoughts on “Unit Test and Mock IHttpContextAccessor

  1. Have you tested this? What mocking library are you using?
    Does not seem possible using the majority of mocking libraries out there

  2. Hello,

    I am trying to use your code to help me implement a unit test but I am getting this error whn utilizing the line to setup the Mock verson of IHttpContextAccessor. Please advise:

    System.ArgumentException : Unsupported expression: … => ….Name in req => req.HttpContext.User.Identity.Name.ToString():
    Type to mock must be an interface, a delegate, or a non-sealed, non-static class

    1. Hey Nicole – Thanks for your query. I see IHttpContextAccessor being an interface, its easy to mock. I don’t see any reason for failing it in your case.
      I have fixed some code formatting in the code as well. Kindly check again.

    2. Hi Nicole,

      I wanted to follow up with your error and see if you found a solution to this. My unit test failing for the same reason

Leave a Reply

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