就我个人而言,我尽量避免在路由约束内执行此类验证,因为以这种方式表达您的意图要困难得多。相反,我使用约束来确保参数的格式/类型正确,并将此类逻辑放入我的控制器中。
在您的示例中,我假设如果该国家/地区无效,那么您将退回到不同的路线(例如“未找到国家/地区”页面)。与接受所有国家/地区参数并在控制器中检查它们相比,依赖您的路由配置的可靠性要低得多(并且更有可能被破坏):
public ActionResult Country(string country)
{
if (country == "france") // lookup to db here
{
// valid
return View();
}
// invalid
return RedirectToAction("NotFound");
}
除此之外,您在此处尝试实现的目标(如前所述)实际上是集成测试。当您发现框架的某些部分妨碍了您的测试时,可能是重构的时候了。在您的示例中,我想测试
- 国家/地区验证正确
- 我的路由配置。
我们可以做的第一件事是将 Country 验证移到一个单独的类中:
public interface ICountryValidator
{
bool IsValid(string country);
}
public class CountryValidator : ICountryValidator
{
public bool IsValid(string country)
{
// you'll probably want to access your db here
return true;
}
}
然后我们可以将其作为一个单元进行测试:
[Test]
public void Country_validator_test()
{
var validator = new CountryValidator();
// Valid Country
Assert.IsTrue(validator.IsValid("france"));
// Invalid Country
Assert.IsFalse(validator.IsValid("england"));
}
我们的CountryRouteConstraint 然后更改为:
public class CountryRouteConstraint : IRouteConstraint
{
private readonly ICountryValidator countryValidator;
public CountryRouteConstraint(ICountryValidator countryValidator)
{
this.countryValidator = countryValidator;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
object country = null;
values.TryGetValue("country", out country);
return countryValidator.IsValid(country as string);
}
}
我们这样绘制路线:
routes.MapRoute(
"Valid Country Route",
"countries/{country}",
new { controller = "Home", action = "Country" },
new { country = new CountryRouteConstraint(new CountryValidator())
});
现在,如果您真的觉得有必要测试 RouteConstraint,您可以独立测试:
[Test]
public void RouteContraint_test()
{
var constraint = new CountryRouteConstraint(new CountryValidator());
var testRoute = new Route("countries/{country}",
new RouteValueDictionary(new { controller = "Home", action = "Country" }),
new RouteValueDictionary(new { country = constraint }),
new MvcRouteHandler());
var match = constraint.Match(GetTestContext(), testRoute, "country",
new RouteValueDictionary(new { country = "france" }), RouteDirection.IncomingRequest);
Assert.IsTrue(match);
}
我个人不会费心执行这个测试,因为我们已经抽象了验证代码,所以这只是测试框架。
为了测试路由映射,我们可以使用 MvcContrib 的TestHelper。
[Test]
public void Valid_country_maps_to_country_route()
{
"~/countries/france".ShouldMapTo<HomeController>(x => x.Country("france"));
}
[Test]
public void Invalid_country_falls_back_to_default_route()
{
"~/countries/england".ShouldMapTo<HomeController>(x => x.Index());
}
根据我们的路由配置,我们可以验证有效的国家/地区映射到国家/地区路由,而无效的国家/地区映射到备用路由。
但是,您的问题的重点是如何处理路由约束的依赖关系。上面的测试实际上是在测试很多东西——我们的路由配置、路由约束、验证器以及可能对存储库/数据库的访问。
如果您依赖 IoC 工具为您注入这些,您将不得不模拟您的验证器和存储库/db,并在您的测试设置中使用您的 IoC 工具注册这些。
如果我们可以控制约束的创建方式会更好:
public interface IRouteConstraintFactory
{
IRouteConstraint Create<TRouteConstraint>()
where TRouteConstraint : IRouteConstraint;
}
您的“真正”实现可以只使用您的 IoC 工具来创建 IRouteConstraint 实例。
我喜欢将我的路由配置放在一个单独的类中,如下所示:
public interface IRouteRegistry
{
void RegisterRoutes(RouteCollection routes);
}
public class MyRouteRegistry : IRouteRegistry
{
private readonly IRouteConstraintFactory routeConstraintFactory;
public MyRouteRegistry(IRouteConstraintFactory routeConstraintFactory)
{
this.routeConstraintFactory = routeConstraintFactory;
}
public void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Valid Country",
"countries/{country}",
new { controller = "Home", action = "Country" },
new { country = routeConstraintFactory.Create<CountryRouteConstraint>() });
routes.MapRoute("Invalid Country",
"countries/{country}",
new { controller = "Home", action = "index" });
}
}
可以使用工厂创建具有外部依赖关系的约束。
这使测试变得更加容易。由于我们只对测试国家/地区路线感兴趣,因此我们可以创建一个只做我们需要的测试工厂:
private class TestRouteConstraintFactory : IRouteConstraintFactory
{
public IRouteConstraint Create<TRouteConstraint>() where TRouteConstraint : IRouteConstraint
{
return new CountryRouteConstraint(new FakeCountryValidator());
}
}
请注意,这次我们使用的 FakeCountryValidator 包含的逻辑刚好足以让我们测试路由:
public class FakeCountryValidator : ICountryValidator
{
public bool IsValid(string country)
{
return country.Equals("france", StringComparison.InvariantCultureIgnoreCase);
}
}
当我们设置测试时,我们将TestRouteFactoryConstraint 传递给我们的路由注册表:
[SetUp]
public void SetUp()
{
new MyRouteRegistry(new TestRouteConstraintFactory()).RegisterRoutes(RouteTable.Routes);
}
这一次,当我们运行路由测试时,我们不测试我们的验证逻辑或数据库访问。相反,我们会在提供有效或无效国家/地区时对我们的路由配置进行单元测试。