1

我有一条这样定义的路线:

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是 null ,所以测试失败。如何将 http 上下文注入约束?

4

1 回答 1

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());
于 2012-09-27T13:29:03.330 回答