dimanche 6 septembre 2015

Unit test controller using UrlHelper with NSubstitute

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

Aucun commentaire:

Enregistrer un commentaire