Model is not checked automatically during unit testing

Here is part of the controller action:

[HttpPost] public ActionResult NewComplaint(Complaint complaint) { if(!ModelState.IsValid) { // some code } // some more code... } 

When the application starts, the model is automatically checked before the if statement is even called. However, when you try to run a unit test, this code does not automatically check.

If I used FormCollection and instead called TryUpdateModel, the check would be done, but I don't want to use it.

I found that calling TryValidateModel (model) before the if statement worked well around the problem; only one extra line of code is required. I would rather get rid of it.

Any ideas why automatic verification does not occur during unit testing, but arises when the application is running?

EDIT: Remember, I am using ASP.NET MVC3 RC1, and I am mocking the controller HTTPContext object, if that matters

+4
source share
1 answer

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 structure (i.e. the fact that the check is done before the action method is called). You should not check this.

You should assume that this part works (because we test it thoroughly) and only check your application code. Therefore, in this case, the only thing you need to make fun of is the return value of ModelState.IsValid , and you can do this by adding a validation error manually:

 ModelState.AddModelError("some key", "some error message") 
+4
source

All Articles