0

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

全球.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") });
}

进口控制器

[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");
}

使用最小起订量进行测试

    [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());
    }
4

1 回答 1

0

您必须设置 HttpMethod,因此在 TestRoutes 方法中添加这些行:

string httpMethod = "GET";
httpContextMock.Setup(c => c.Request.HttpMethod).Returns(httpMethod);
于 2012-11-29T21:55:12.453 回答