Avoid Duplicate Mocking Code in Unit Tests

Published: Wed May 27 2015

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.

public class UnitTestContext { public Mock CustomerRepository { get; set; } public Mock ContractRepository { get; set; } public UnitTestContext() { CustomerRepository = new Mock(); CustomerRepository.Setup(r => r.GetCustomerById(It.IsAny<int>())).Returns(new Customer()); ContractRepository = new Mock<IContractRepository>(); ContractRepository.Setup(r => r.GetContractById(It.IsAny<int>())).Returns(new Contract()); } } [TestClass] public class TestsUsingRepositories { [TestMethod] public void Some_Test_In_Need_Of_A_Mocked_Repository() { UnitTestContext context = new UnitTestContext(); //Inject into code that needs ContractRepository. var contractRepository = context.ContractRepository; //Inject into code that needs CustomerRepository. var customerRepository = context.CustomerRepository; } }