2012-09-27 121 views
1

單元測試ASP MVC路線我有一個是這樣定義的路由:與約束

routes.MapRoute(
      "Default", // Route name 
      "{controller}/{action}/{id}", // URL with parameters 
      new { controller = "Home", action = "Index", id = UrlParameter.Optional, area = "" }, // Parameter defaults 
      new { home = new HomePageConstraint() } 
     ); 

public class HomePageConstraint : IRouteConstraint 
{ 
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 
     return !httpContext.Request.RawUrl.StartsWith("/home", StringComparison.InvariantCultureIgnoreCase); 
    } 
} 

,我試圖來測試它是這樣的:

[Test] 
public void Home_Load_Homepage() 
{ 
    "~/".ShouldMapTo<HomeController>(x => x.Index()); 
} 

我是問題httpContext爲空,所以測試失敗。我怎樣才能將http上下文注入約束?

回答

1

最後,我這樣做:

var context = new FakeHttpContext("~/"); 
var fakeRequest = new FakeRequest("~/", new Uri("http://localhost/"), new Uri("http://localhost/")); 
context.SetRequest(fakeRequest); 

var route = RouteTable.Routes.GetRouteData(context); 

route.ShouldMapTo<HomeController>(x => x.Index());