1

帮手:

public static MvcHtmlString RouteLink(this HtmlHelper helper, String linkText, String routeName, Object routeValues, String status)
{
    if (status.ToLower() == "post-game" || status.ToLower() == "mid-game")
    {
        return helper.RouteLink(linkText, routeName, routeValues);
    }

    return MvcHtmlString.Create(" ");
}

单元测试:

[TestMethod]
public void RouteLinkTest()
{
    var httpContext = new Mock<HttpContextBase>();
    var routeData = new Mock<RouteData>();
    var viewContext = new ViewContext { HttpContext = httpContext.Object, RouteData = routeData.Object };

    var helper = new HtmlHelper(viewContext, new Mock<IViewDataContainer>().Object);
    var target01 = helper.RouteLink("Linking Text", "route-name", new { id = "id" }, "status");
    Assert.IsNotNull(target01);
}

错误:

Test method Web.Tests.Extensions.HtmlHelpersTest.RouteLinkTest threw exception: 
System.ArgumentException: A route named 'route-name' could not be found in the route collection.
Parameter name: name

问题:如何模拟路线以获得正确的路线名称?

4

1 回答 1

0

而不是模拟路由值告诉 MvcApplication 注册它们

  var routes = new RouteCollection();
  MvcApplication.RegisterRoutes(routes);

当我必须在我的控制器中使用类似的东西测试一些 redirectToAction 时,我会使用它

  var controller = GetController();
  var httpContext = Utilities.MockControllerContext(true, false).Object;
  controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), controller);
  var routes = new RouteCollection();
  MvcApplication.RegisterRoutes(routes);
  controller.Url = new UrlHelper(new RequestContext(httpContext, new RouteData()), routes);
  var result = controller.DoMyStuff();
  Assert.IsInstanceOfType(typeof(RedirectResult), result);
  var actual = (RedirectResult)result;
  Assert.AreEqual("/myurl", actual.Url.ToString());

我从来没有测试过像你这样的助手,但我认为这应该可行

于 2012-04-05T16:38:15.310 回答