2016-09-20 144 views
0

我已经看到一些关于测试微软路由的非常有用的文章。特别是www.strathweb.com/2012/08/testing-routes-in-asp-net-web-api/似乎只处理WebApi。虽然相似,但它们并不相同。如果我有一个MVC应用程序,我如何看到将为给定的URL调用的方法。这似乎归结为创建一个“请求”,可以传递给HttpControllerContext的构造函数,并在测试中获取对“当前”配置(如HttpConfiguration)的引用。想法?测试URL到MVC控制器方法

谢谢。

回答

1

测试传入URL

如果你需要测试的路线,你需要从MVC框架嘲笑三类:HttpRequestBase,HttpContextBase和HttpResponseBase(仅用于传出URL's)

private HttpContextBase CreateHttpContext(string targetUrl = null, string httpMethod = "GET") 
    { 
     // create mock request 
     Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>(); 
     // url you want to test through the property 
     mockRequest.Setup(m => m.AppRelativeCurrentExecutionFilePath).Returns(targetUrl); 
     mockRequest.Setup(m => m.HttpMethod).Returns(httpMethod); 

     // create mock response 
     Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>(); 
     mockResponse.Setup(m => m.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(s => s); 

     // create the mock context, using the request and response 
     Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>(); 
     mockContext.Setup(m => m.Request).Returns(mockRequest.Object); 
     mockContext.Setup(m => m.Response).Returns(mockResponse.Object); 

     // return the mock context object 
     return mockContext.Object; 
    } 

然后您需要一个额外的帮助方法,让我们指定要测试的URL和预期的段变量以及其他变量的对象。

 private void TestRouteMatch(string url, string controller, string action, 
     object routeProperties = null, string httpMethod = "GET") 
    { 
     // arrange 
     RouteCollection routes = new RouteCollection(); 
     // loading the defined routes about the Route-Config 
     RouteConfig.RegisterRoutes(routes); 
     RouteData result = routes.GetRouteData(CreateHttpContext(url, httpMethod)); 

     // assert 
     Assert.IsNotNull(result); 
     // here you can check your properties (controller, action, routeProperties) with the result 
     Assert.IsTrue(.....); 
    } 

你鸵鸟政策需要在测试methodes来定义你的路线,因为他们是直接加载使用在RouteConfig的RegisterRoutes方法。

该入站网址匹配工作的机制。

GetRouteData(HttpContextBase httpContext) 

referencesource.microsoft

框架调用为每个路由表条目该方法中,直到thems之一返回一个非空值。

你要调用的辅助方法,例如通过这种方式

[TestMethod] 
    public void TestIncomingRoutes() { 
     // check for the URL that is hoped for 
     TestRouteMatch("~/Home/Index", "Home", "Index"); 
    } 

的方法来检查你期待的URL在上面的例子中,电话在主控制器中的索引操作。您必须在URL前加上波浪号(〜),这正是ASP.NET Framework向路由系统呈现URL的方式。

在参考书籍亚当弗里曼临ASP.NET MVC 5我可以推荐给每个ASP.NET MVC开发者!

+0

当我这样做时,我得到一个InvalidOperationException在 routes.MapMvcAttributeRoutes(); ,并提示“在应用程序的预启动初始化阶段无法调用此方法”。可以修改这个方法来获取属性路由吗? –

+0

@KevinBurton将MapMvcAttributeRoutes移动到Global.asax.cs文件 - RouteTable.Routes.MapMvcAttributeRoutes(); – Diginari