I'm using ASP.NET MVC 2 with DataAnnotation attributes sprinkled on properties like so:
public class LogOnViewModel
{
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string Domain { get; set; }
}
I have a unit test which checks that the current view is rendered when validation fails. However, I'm manually adding errors to the ModelState
to get it to work:
[Test]
public void TestThatLogOnActionRedirectsToLogOnViewIfValidationFails()
{
//create a invalid view model
var model = new LogOnViewModel {UserName = "jsmith"};
//Can I avoid doing this manually?
//populate Model State Errors Collection
_accountController.ModelState.AddModelError("FirstName", "First Name Required");
_accountController.ModelState.AddModelError("LastName", "Last Name Required");
var result = _accountController.LogOn(model);
result.AssertViewRendered()
.ForView(Constants.Views.LogOn)
.WithViewData<LogOnViewModel>();
}
Is there a way to interact with the ModelBinder either directly or indirectly in a unit test? For example:
[Test]
public void TestThatLogOnActionRedirectsToLogOnViewIfValidationFails()
{
//create a invalid view model
var model = new LogOnViewModel {UserName = "jsmith"};
//validate model
//not sure about the api call...
var validationResults = new DataAnnotationsModelBinder().Validate(model);
_accountController.ModelState.Merge(validationResults);
var result = _accountController.LogOn(model);
result.AssertViewRendered()
.ForView(Constants.Views.LogOn)
.WithViewData<LogOnViewModel>();
}