Unit testing model validation with MVC’s DataAnnotations

By | June 21, 2013

In a previous post, I mentioned that model validation should be tested separately from controller logic. I will demonstrate a way of unit testing the validation of models implemented with System.ComponentModel.DataAnnotations.

It is actually quire easy to unit test model validation. Models are inherently easy to test separately due to their POD (Plain Old Data) nature. We can instantiate them directly. Moreover, DataAnnotations provides us with the necessary interface to run the validation against a model object completely separately from the rest of the application.

A first model validation test class

Here is a basic model that we will unit test for the demonstration:

As you can see, it is quite simple. We’ll go directly to the unit test implementation.

The strategy we are going to use consists in basing each test case on a valid model instance, then modifying it in such a way that it triggers one single validation error. We end up with a skeleton unit test class like this:

Some explanation:

  • ValidateRule() implements the test itself. However, it gets the specifications for each test via an argument. 
  • ValidateRule_Source() provides the specs for our test.
  • class ValidateRuleSpec holds the specifications. Its ToString() uses the spec values to render a distinct string per test. This makes unit test reports easy to read. In case of failure, you know exactly which spec failed.

And now the implementation of our ValidateRule_Source():

Refining the solution

This works but can be improved. Most of the functionality can be abstracted. The actual test need only provide the valid model object and the specifications. A bit of refactoring yields a nicer design for our test:

Notice how we trimmed CreatePersonModelValidationTests to a minimum. The class ModelValidationTestsBase can now be used for most of our model validation unit tests.

What do you think?

Leave a Reply