How to Integrate LinqToSql with Metadata Annotations
-
23-08-2019 - |
Question
I'm just getting started on a new MVC project, and like a good boy I am trying to defer going to the DB for as long as possible. Here's the scoop:
- I'm planning on using the ComponentModel.DataAnnotations decorations.
- I'm also planning on using LinqToSql
Is is possible to write a unit test against the DataAnnotations metadata classes? I don't want to put a schema such until as late as possible but I'd still like to write tests to validate the model.
Any ideas on a good approach? Maybe something completely different?
Solution
Brad Wilson wrote a great blog post about using DataAnnotations and unit testing them; http://bradwilson.typepad.com/blog/2009/04/index.html
The gist of the testing strategy is this:
- Write a test to check to make sure you are using the DataAnnotationsModelBinder as the default binder.
- Use reflection to make sure the DataAnnotation attributes you have decorated the model properties with are what you expect.
- When testing the Edit or Create controller actions, artificially inject ModelErrors to test that you are handling them as expected.
The rationale is that you treat System.ComponentModel.DataAnnotations like a piece of infrastructure and just test how you have utilized it.