如何模拟Url.Action

时间:2014-03-18 07:59:48

标签: c# asp.net-mvc unit-testing moq

方法I尝试单元测试返回:

return Json(new { ok = true, newurl = Url.Action("Index") });

但是这一行会引发NullReferenceException,这是由这部分回复引起的:

newurl = Url.Action("Index")

我试图用以下方法制作:

Request.SetupGet(x => x.Url).Returns(// Data here);

没有任何影响。

你能建议我解决吗?

2 个答案:

答案 0 :(得分:5)

以下是使用NSubstitute模拟UrlHelper的方法。它与其他模拟库非常相似:

UrlHelper Url { get; set; }

[TestFixtureSetUp]
public void FixtureSetUp()
{
    var routes = new RouteCollection();
    RouteConfig.RegisterRoutes(routes);

    var httpContext = Substitute.For<HttpContextBase>();
    httpContext.Response.ApplyAppPathModifier(Arg.Any<string>())
        .Returns(ctx => ctx.Arg<string>());
    var requestContext = new RequestContext(httpContext, new RouteData());
    Url = new UrlHelper(requestContext, routes);
}

// Pages

[Test]
public void HomePage()
{
    Url.Action("home", "pages").ShouldEqual("/");
}

[Test]
public void PageDetails()
{
    Url.Action("details", "pages", new { slug = "contact" }).ShouldEqual("/pages/contact");
}

答案 1 :(得分:0)

如果你想将一个模拟的UrlHelper附加到一个真正的Controller上,那么当你在Controller上调用一个Action时,它不会在UrlHelper上崩溃,这就是我们所做的(快速和脏版本):

    public class MyController : Controller
    {
        [HttpPost]
        public ActionResult DoSomething(int inputValue)
        {
            var userName = User.UserName();
            return Json(new {
                redirectUrl = Url.Action("RedirectAction", "RedirectController"),
                isRedirect = true,
            });
        }  
    }

    [Test]
    public void Test1()
    {
        var sb = new StringBuilder();

        var response = Substitute.For<HttpResponseBase>();

        response.When(x => x.Write(Arg.Any<string>())).Do(ctx => sb.Append(ctx.Arg<string>()));

        var httpContext = Substitute.For<HttpContextBase>();

        httpContext.Response.Returns(response);
        httpContext.User.Identity.Name.Returns("TestUser");

        var controller = new MyController();

        controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), myController);
        controller.Url = Substitute.For<UrlHelper>();
        controller.Url.Action(Arg.Any<string>(), Arg.Any<string>()).Returns("anything");

        controller.DoSomething(1);
    }