致以验证我已经根据下面的文章创建了自己的模型绑定: http://www.howmvcworks.net/OnModelsAndViewModels/TheBeautyThatIsTheModelBinderMVC变化ModelBinder的单元测试
在我的应用程序扩展我的人实体是这样的:
[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创建活动和提供的电子邮件无效,ModelState.Valid场是假的。
现在我喜欢的创建方法创建单元测试:
[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?
谢谢!