1

I'm using MVC5 and NSubstitute. I'm trying to create unit test to verify the model is being properly created for some controller actions.

The problem I have is that the controller is using a model within which I have something along the lines of:

Url = new UrlHelper(Request.RequestContext).Action("Browse")

Any time I try to test this controller method, I get a null object exception. I have tried a lot of different ways to try and mock the context, but it never seems to quite work. Can anyone help?

I've referred to many SO question including; ASP.NET MVC: Unit testing controllers that use UrlHelper

Which isn't so helpful to me as I'm using NSubstitute.

I was trying to use a MockHttpContext helper method I had found:

       public static T MockHttpContext<T>(this T controller) where T : Controller
    {
        controller.ControllerContext = new ControllerContext
        {
            HttpContext = GetHttpContextMock()
        };
        controller.Url = new UrlHelper(controller.ControllerContext.RequestContext);
        return controller;
    }

    private static HttpContextBase GetHttpContextMock()
    {
        var routes = new RouteCollection();

        var actionExecutingContext = Substitute.For<ActionExecutingContext>();
        var httpContextBase = Substitute.For<HttpContextBase>();
        var httpServerUtilityBase = Substitute.For<HttpServerUtilityBase>();
        var httpResponseBase = Substitute.For<HttpResponseBase>();
        var httpRequestBase = Substitute.For<HttpRequestBase>();
        var httpSessionStateBase = Substitute.For<HttpSessionStateBase>();

        actionExecutingContext.HttpContext.Returns(httpContextBase);
        httpContextBase.Request.ApplicationPath.Returns("");
        httpContextBase.Response.ApplyAppPathModifier(Arg.Any<string>())
            .Returns(ctx => ctx.Arg<string>());
        httpContextBase.Request.Returns(httpRequestBase);
        httpContextBase.Response.Returns(httpResponseBase);
        httpContextBase.Server.Returns(httpServerUtilityBase);
        httpContextBase.Session.Returns(httpSessionStateBase);
        httpRequestBase.Cookies.Returns(new HttpCookieCollection());

        return httpContextBase;
    }
Community
  • 1
  • 1
pierre
  • 1,235
  • 1
  • 13
  • 30

1 Answers1

0

I was trying to do the same thing. This worked for me:

controller.Url = Substitute.For<UrlHelper>();
controller.Url.Action(Arg.Any<string>(), Arg.Any<string>()).Returns("something");

Then when I call my controller action, it does not crash when dereferencing the UrlHelper. Of course you have to mock up (NSubstitute) the controller properly. I hope this works. I can post more code for mocking the controller if you need.

Evan
  • 457
  • 4
  • 14