还没有找到另一个ASP.NET MVC路由

时间:2012-11-29 11:16:41

标签: asp.net-mvc asp.net-mvc-routing

我正在尝试为MVC 3路线编写测试但仍未获得匹配。为什么这不适用于测试?我要离开http://haacked.com/archive/2007/12/17/testing-routes-in-asp.net-mvc.aspx,看看MVC代码,它可能与VirtualPathProvider有关吗?

Global.asax中

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "import_DownloadTemplate",
        "{culture}/Client/{clientId}/DownloadTemplate",
        new { controller = "Import", action = "DownloadTemplate" },
        new { httpMethod = new HttpMethodConstraint("GET") });
}

ImportController

[HttpGet]
[Cache(Order = 1)]
[OutputCache(Order = 2, Duration = 60, VaryByParam = "*")]
public ActionResult DownloadTemplate(string culture, long clientId)
{
    byte[] result = this.repository.GetTemplateByClientId(clientId, culture);

    return new FileContentResult(result, "application/vnd.ms-excel");
}

使用MOQ进行测试

    [TestMethod]
    public void TestRoutes()
    {
        string url = "~/en-us/Client/1/DownloadTemplate";

        var httpContextMock = new Mock<HttpContextBase>();
        httpContextMock.Setup(c => c.Request.AppRelativeCurrentExecutionFilePath)
            .Returns(url);

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

        var routeData = routes.GetRouteData(httpContextMock.Object);
        // routeData is null!

        Assert.AreEqual("import", routeData.Values["controller"].ToString());
        Assert.AreEqual("DownloadTemplate", routeData.Values["action"].ToString());
    }

1 个答案:

答案 0 :(得分:0)

你必须设置HttpMethod,所以在TestRoutes方法中添加这些行:

string httpMethod = "GET";
httpContextMock.Setup(c => c.Request.HttpMethod).Returns(httpMethod);