4

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

xTRUMANx
  • 1,035
  • 1
  • 8
  • 12

1 Answers1

4

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")
marcind
  • 52,944
  • 13
  • 125
  • 111
  • Man, now I feel silly. Should of just done that or mocked that. Throughout my tests, I create an object/formCollection with all the necessary properties/entries to make it pass validation instead of just setting the ModelState via mocks. – xTRUMANx Dec 11 '10 at 11:43
  • 7
    marcind, I get that testing the framework is out of scope for most unit testing. However, testing should indicate if the correct data annotations have been specified. – wilk Dec 16 '10 at 12:34