I have following web Api controller method.
When I run this code through web, HttpContext.Current
is never null
and give desired value.
public override void Post([FromBody]TestDTO model)
{
var request = HttpContext.Current.Request;
var testName = request.Headers.GetValues("OS Type")[0];
// more code
}
However, when I call this method from Unit Test
, HttpContext.Current is always null.
How do i fix it?
I have added FakeHttpContext nuget package and it worked for me.
All you need is
From unit-testing-controllers-in-web-api
During unit tests
HttpContext
is alwaysnull
as it is usually populate by IIS. You have a few options around this.Sure, you could mock the
HttpContext
, (which you shouldn't really do - Don't mock HttpContext!!!! He doesn't like to be mocked!),. You should really try to stay away from tight coupling withHttpContext
all over your code. Try constraining it to one central area (SRP);Instead figure out what is the functionality you would like to achieve and design an abstraction around that. This will allow for your code to be more testable as it is not so tightly coupled to
HttpContext
.Based on your example you are looking to access header values. This is just an example of how to change your thinking when it comes to using
HttpContext
.Your original example has this
When you are looking for something like this
Well then create a service that provides that
which could have a concrete implementation like
Now in your controller you can have your abstraction instead of having tight coupling to
HttpContext
You can later inject your concrete type to get the functionality you want.
For testing you then swap dependencies to run your test.
If the method under test is your
Post()
method you can create a fake dependency or use a mocking frameworkTo install FakeHttpContext, run the following command in the Package Manager Console (PMC)
And then use it like this:
Visit https://www.nuget.org/packages/FakeHttpContext to install the package
See examples on Github: https://github.com/vadimzozulya/FakeHttpContext#examples
Hope this will help :)