帮助者:
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
问题: 如何模拟路线以获得正确的路线名称?
答案 0 :(得分:0)
而不是mockin the routevalues告诉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());
我从未测试过像你这样的帮手,但我认为这应该有效