2012-11-29 193 views
0

我正在嘗試爲MVC 3路由編寫測試,但仍未找到匹配項。爲什麼這在測試中不起作用?我正在關閉http://haacked.com/archive/2007/12/17/testing-routes-in-asp.net-mvc.aspx,並從查看MVC代碼,它可能與VirtualPathProvider有關?使用MOQ未找到另一個ASP.NET MVC路由

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

回答

0

您必須設置列舉HTTPMethod,所以加在TestRoutes方法這些線路

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

測試:

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

你解決了你的問題嗎? –