devlife
devlife

Reputation: 16145

NullReferenceException when calling UrlHelper.Content(string) in a unit test

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);
}

Upvotes: 3

Views: 3072

Answers (1)

Mike Parkhill
Mike Parkhill

Reputation: 5551

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().

[Test]
public void DummyTest() {
    var context = new Mock<HttpContextBase>();
    context.Setup( c => c.Request.ApplicationPath ).Returns( "/tmp/testpath" );
    context.Setup( c => c.Response.ApplyAppPathModifier( It.IsAny<string>( ) ) ).Returns( "/mynewVirtualPath/" );
    RequestContext requestContext = new RequestContext( context.Object, new RouteData() );
    UrlHelper urlHelper = new UrlHelper( requestContext );

    string path = urlHelper.Content( "~/test.png" );

    Assert.IsNotNullOrEmpty( path );
}

I found the details for this in the following thread: Where does ASP.NET virtual path resolve the tilde "~"?

Upvotes: 10

Related Questions