سؤال

I have a route that is defined like this:

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);
    }
}

And I am trying to test it like this:

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

The problem I have is that the httpContext is null, so the test fails. how can I inject http context into a constraint?

هل كانت مفيدة؟

المحلول

In the end I did this:

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());
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top