使用UrlHelper和NSubstitute的单元测试控制器

时间:2015-09-07 00:58:10

标签: unit-testing asp.net-mvc-5 nsubstitute

我正在使用MVC5和NSubstitute。我正在尝试创建单元测试以验证是否正在为某些控制器操作正确创建模型。

我遇到的问题是控制器正在使用一个模型,其中我有以下几点:

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

每当我尝试测试这个控制器方法时,我都会得到一个null对象异常。我已经尝试了很多不同的方法来尝试和模拟上下文,但它似乎从来没有完全奏效。有人可以帮忙吗?

我提到了许多SO问题,包括; ASP.NET MVC: Unit testing controllers that use UrlHelper

对我来说,这对我来说没什么用,因为我正在使用NSubstitute。

我试图使用我找到的MockHttpContext辅助方法:

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

1 个答案:

答案 0 :(得分:0)

我试图做同样的事情。这对我有用:

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

然后当我调用我的控制器动作时,取消引用UrlHelper时它不会崩溃。当然你必须正确地模拟(NSubstitute)控制器。我希望这有效。如果需要,我可以发布更多用于模拟控制器的代码。

相关问题