为什么路由测试失败但路由在运行应用程序时有效?

时间:2010-10-01 08:20:25

标签: c# asp.net-mvc-2 nunit moq

我有默认的路线设置:

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控制器。为什么是这样?我的测试出了什么问题?

1 个答案:

答案 0 :(得分:3)

AssertRoute中,您要将httpContext.Request.AppRelativeCurrentExecutionFilePath设置为始终返回"~/"而不是您要测试的网址。