Let's say I have this unit test:
[Test]
public void LastNameShouldNotBeEmpty()
{
ExampleController controller = new ExampleController();
Person editedPerson = new Person { FirstName = "j", LastName = "" };
controller.EditPerson(editedPerson);
Assert.AreEqual(controller.ModelState.IsValid, false);
}
And this code:
public class ExampleController : Controller
{
public ActionResult EditPerson(int personId)
{
// Serve up a view, whatever
return View(Person.LoadPerson(personId));
}
[HttpPost]
public ActionResult EditPerson(Person person)
{
if (ModelState.IsValid)
{
// TODO - actually save the modified person, whatever
}
return View(person);
}
}
public class Person
{
public string FirstName { get; set; }
[Required] public string LastName { get; set; }
}
It's bothering me that if I TDD out a requirement that the LastName can't be empty, I can't satisfy the test using DataAnnotation attributes (the [Required] before the LastName declaration on Person) because when the controller's action method is invoked from a unit test, the MVC infrastructure hasn't gotten a chance to apply the validation it does during model binding.
(If I manually performed validation in the controller's EditPerson method, though, and added an error to the ModelState, that would be verifiable from a unit test.)
Am I missing something? I'd like to specify the validation behavior of my system using unit tests, but I'm not sure how to satisfy a unit test unless I abandon DataAnnotation attributes altogether and perform validation manually inside my controller's action methods.
I hope the intent of my question is clear; is there a way to force true model binding to execute (including its validation behavior, to test that I haven't forgotten important validation attributes) from an automated unit test?
Jeff