Avoid Duplicate Mocking Code in Unit Tests
When adding a mocking framework to your unit tests, you run the risk of introducing a lot of duplicated mocking code. This is especially true when mocking fundamental classes like data access repositories. I've found that it pays to move this mocking code out to a common UnitTestContext class and reuse it in all your test fixtures.
The following code shows an example of how to do this. This specific example uses MOQ, but you can apply the same principle to other frameworks as well.
Mocked versions of both CustomerRepository and ContractRepository are now available to all tests. I find that any mocking code that can be shared between different tests is a candidate for the UnitTestContext. There might be a minor performance penalty when creating a large UnitTestContext, but the benefits of avoiding duplicate code more than makes up for that.