Tips & tricks for unit testing in .NET Core 3: Mocking IHttpContextAccessor
I wanted to write this article because I recently came across an interesting test case. This involved testing a factory that selected a service instance in the DI system from a service name. To be able to test this case, I had to mock the IHttpContextAccessor interface and a little bit more … Let’s see how I did it.
Let’s look at our test case, here we have two different instances of possible services and then according to a parameter named “name” we have to test if the instance is correctly returned:
Let’s take a look on how IHttpContextAccessor works:
We need to create an instance (a mock) of IHttpContextAccessor , then access to an instance of HttpContext and finally access to an instance of IServiceProvider (RequestServices). Once we are done we can test if GetService returns the proper instance.
How to achieve that?
- Step 1, mock IHttpContextAccessor
- Step 2, create an instance of HttpContext with DefaultHttpContext class
- Step 3, populate an instance of IServiceCollection and register required service instances
- Step 4, build an instance of IServiceProvider from an IServiceCollection instance
- Step 5, assign IServiceProvider instance to RequestServices
Here is what the test looks like:
Hope this article was helpful 🙂