我有默认的路线设置:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Shortie", // Route name
"{controller}/{id}", // URL with parameters
new { controller = "Ettan", action = "Index", id = "id" } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Ettan", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
我在nunit / resharper中运行以下测试,使用Moq设置HttpContext:
[TestFixture]
public class RoutesTests
{
[Test]
public void RoutingTest()
{
var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
AssertRoute(routes, "~/", "Ettan", "Index");
AssertRoute(routes, "~/Artikel/123", "Artikel", "Index");
}
public static void AssertRoute(RouteCollection routes, string url, string controller, string action)
{
var httpContext = new Mock<HttpContextBase>();
httpContext.Setup(c => c.Request.AppRelativeCurrentExecutionFilePath).Returns("~/");
var routeData = routes.GetRouteData(httpContext.Object);
Assert.IsNotNull(routeData);
Assert.AreEqual(controller, routeData.Values["Controller"]);
Assert.AreEqual(action, routeData.Values["Action"]);
}
}
我期待AssertRoutes成功,但第二个失败(它路由到controller =“Ettan”,而不是controller =“Artikel”)。
但是,如果我运行mvc应用程序并浏览到localhost / Artikel / 123,我将被路由到Artikel控制器。为什么是这样?我的测试出了什么问题?
答案 0 :(得分:3)
在AssertRoute
中,您要将httpContext.Request.AppRelativeCurrentExecutionFilePath
设置为始终返回"~/"
而不是您要测试的网址。