3

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);
}
tereško
  • 58,060
  • 25
  • 98
  • 150
devlife
  • 15,275
  • 27
  • 77
  • 131

1 Answers1

10

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 "~"?

Community
  • 1
  • 1
Mike Parkhill
  • 5,511
  • 1
  • 28
  • 38
  • I tried the suggestions from those links to no avail. It might be worth pointing out that the test passes if you remove the "~" from the path. – devlife Oct 03 '12 at 01:15
  • From the MSDN article: "If the specified content path does not start with the tilde (~) character, this method returns contentPath unchanged." So, if you take the tilde out it's not doing any actual work under the hood. – Mike Parkhill Oct 03 '12 at 01:17