測試傳入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開發者!
當我這樣做時,我得到一個InvalidOperationException在 routes.MapMvcAttributeRoutes(); ,並提示「在應用程序的預啓動初始化階段無法調用此方法」。可以修改這個方法來獲取屬性路由嗎? –
@KevinBurton將MapMvcAttributeRoutes移動到Global.asax.cs文件 - RouteTable.Routes.MapMvcAttributeRoutes(); – Diginari