带有约束的单元测试ASP MVC路由

时间:2012-09-27 11:17:00

标签: asp.net-mvc-3 unit-testing routing mvccontrib

我的路线定义如下:

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 个答案:

答案 0 :(得分: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());