to extend my validation I have created my own model binder based on following article: http://www.howmvcworks.net/OnModelsAndViewModels/TheBeautyThatIsTheModelBinder
In my application I extend my Person entity like this:
[MetadataType(typeof (PersonMetaData))] public partial class Person { }
public class PersonMetaData { [CustomRegularExpression(@"(\w|.)+@(\w|.)+", ErrorMessage = "Email is invalid")] public string Name; }
My global.asax looks like this:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
//Change default modelbinding
ModelBinders.Binders.DefaultBinder = new CustomModelBinder();
}
When I call the create event for my PersonController and the provided email is invalid, the ModelState.Valid field is false.
Now I like to create a unit test for the create method:
[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.");
}
When I debug the code the ModelState.Valid attribute is telling me that there is no error. I think that the registration of the DefaultBinder was not sucessfull.
How can I register my DefaultBinder in my unit test?
Thank you!