Reputation: 1035
Here's part of a controller action:
[HttpPost]
public ActionResult NewComplaint(Complaint complaint)
{
if(!ModelState.IsValid)
{
// some code
}
// some more code...
}
When running the application, the model is automatically validated before the if statement is even called. However, when attempting to unit test this code, the automatic validation does not occur.
If I were to use a FormCollection and call TryUpdateModel instead, the validation would occur but I don't want to use that.
I've found that calling TryValidateModel(model) before the if statement works around the problem well; only requiring one extra line of code. I'd rather get rid of it however.
Any ideas why the automatic validation does not occur when unit testing but occurs when the application is running?
EDIT: Forgot to mention, I'm using ASP.NET MVC3 RC1 and I'm mocking the HTTPContext object of the controller if that makes any difference
Upvotes: 4
Views: 938
Reputation: 53183
Validation occurs during model binding (and TryUpdateModel performs model binding).
But I think the problem is that what you are trying to test is the MVC framework (i.e. the fact that validation occurs before an action method is invoked). You shouldn't test that.
You should assumet that that part just works (because we test it extensively) and only test your application code. So in this case, the only thing you need to mock is the return value of ModelState.IsValid
and you can do that by adding a validation error manually:
ModelState.AddModelError("some key", "some error message")
Upvotes: 4