ASP.NET MVC 2 allows you to do data validation, either using the de-facto Data Annotations or plugging in your own, much in the same way xVal work. If you’re interested in seeing how that works, take a look at this post.
This post however concerns testing. Here’s some code:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Customer customer)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View(customer);
}
This code checks to see if my model is valid. If it is, it then saves it (not in the code) and redirects to the index action, thus producing a RedirectToActionResult. If it is not valid, it will return a ViewResult. Here’s the model:
public class Customer
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
Given the previous, what would you expect the following test to do? Pass or fail?
[Fact]
public void wont_give_you_any_hints()
{
var controller = new CustomerController();
var customer = new Customer();
customer.FirstName = "Jak a.k.a. Casey";
customer.LastName = String.Empty;
var result = controller.Create(customer);
Assert.IsType(typeof(ViewResult), result);
}
I’ll give you a hint. It fails. Now I understand why it fails. My problem however is that for me to test my model is valid is going to force me to change the way I have to write my code, and potentially make it less readable.