I wish to use unit testing in a project that I am involved in. The solution has a UI layer, a Domain Logic Layer and Database base all seperated into physically seperated dlls, so it is pretty standard nowdays.
In the Domain layer we have a class that makes use of
new HttpContextWrapper(HttpContext.Current)
to get the context of the current request to compile a Url for dynamic menus. And as expected everything works fine when running in a web environment as this HttpContext.Current is always set.
However when I come to unit test a controller I hit this line of code and get a Null reference exception.
After some research I have many articles that suggest using Mock to create a Fake Http Context and set this when creating the controller like so:
var httpContext = FakeHttpContext();
ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
controller.ControllerContext = context;
But this still does not change the HttpContxt.Current and I am still getting a null reference exception.
What am I doing wrong / How can I resolve this exception?
You can’t use HttpContext.Current in this way. At one of my previous gigs, in order to account for this, we had to create a separate wrapper class and access that property.
Using statics is a very common problem in unit testing.
Per your request for an update:
Then in your usage you might do something like:
and: