为了扩展我的验证,我根据以下文章创建了自己的模型绑定器:http: //www.howmvcworks.net/OnModelsAndViewModels/TheBeautyThatIsTheModelBinder
在我的应用程序中,我像这样扩展我的 Person 实体:
[MetadataType(typeof (PersonMetaData))] 公共部分类 Person { }
公共类 PersonMetaData { [CustomRegularExpression(@"(\w|.)+@(\w|.)+", ErrorMessage = "电子邮件无效")] 公共字符串名称;}
我的 global.asax 看起来像这样:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
//Change default modelbinding
ModelBinders.Binders.DefaultBinder = new CustomModelBinder();
}
当我为我的 PersonController 调用 create 事件并且提供的电子邮件无效时,ModelState.Valid 字段为 false。
现在我想为 create 方法创建一个单元测试:
[TestInitialize()]
public void MyTestInitialize()
{
RegisterRoutes(RouteTable.Routes);
//Change default modelbinding
ModelBinders.Binders.DefaultBinder = new CustomModelBinder();
}
/// <summary>
///A test for Create
///</summary>
// TODO: Ensure that the UrlToTest attribute specifies a URL to an ASP.NET page (for example,
// http://.../Default.aspx). This is necessary for the unit test to be executed on the web server,
// whether you are testing a page, web service, or a WCF service.
[TestMethod()]
public void CreateTest()
{
PersonController controller = new PersonController();
Person Person = new Person();
Person.Email = "wrognmail.de
var validationContext = new ValidationContext(Person, null, null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(Person, validationContext, validationResults, true);
foreach (var validationResult in validationResults)
{
controller.ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage);
}
ActionResult actual;
actual = controller.Create(Person);
// Make sure that our validation found the error!
Assert.IsTrue(controller.ViewData.ModelState.Count == 1, "err.");
}
当我调试代码时,ModelState.Valid 属性告诉我没有错误。我认为 DefaultBinder 的注册没有成功。
如何在单元测试中注册我的 DefaultBinder?
谢谢!