I have a few UrlHelper extension methods that I’d like to unit test. However, I’m getting a NullReferenceException from the UrlHelper.Content(string) method when the path begins with “~/”. Anyone know what the issue is?
[Test]
public void DummyTest()
{
var context = new Mock<HttpContextBase>();
RequestContext requestContext = new RequestContext(context.Object, new RouteData());
UrlHelper urlHelper = new UrlHelper(requestContext);
string path = urlHelper.Content("~/test.png");
Assert.IsNotNullOrEmpty(path);
}
When you create the UrlHelper with the RouteContext the HttpContext is null in your unit test environment. Without it you’ll hit a lot of NullReferenceExceptions when you try to call any methods that rely on it.
There are a number of threads out there on mocking the various web contexts. You can check out this one:
How do I mock the HttpContext in ASP.NET MVC using Moq?
or this one
Mock HttpContext.Current in Test Init Method
EDIT:
The following will work. Note you need to mock the HttpContext.Request.ApplicationPath and the HttpContext.Response.ApplyAppPathModifier().
I found the details for this in the following thread:
Where does ASP.NET virtual path resolve the tilde "~"?