Using a container for unit testing is a good way to insulate your tests from changes in object construction. Typically my first test will be something pretty boring just to get the process started. A few tests later, the real behavior comes out along with new dependencies. Rather than having to go back and add the dependencies to all the tests I’ve already written, I like to use a container to build up the object I’m testing.
To streamline this process, I thought it would be handy to use a container extension to auto generate mocks for any required interface that wasn’t explicitly registered. The best way I can explain this is with code, so here it is:
1234567891011121314151617181920
[SetUp]publicvoidSetUp(){container=newUnityContainer().AddNewExtension<AutoMockingContainerExtension>();}[Test]publicvoidShould_be_really_easy_to_test(){container.RegisterMock<IDependencyThatNeedsExplicitMocking>().Setup(d=>d.MyMethod(It.IsAny<int>())).Returns("I want to specify the return value");varservice=container.Resolve<ServiceWithThreeDependencies>();varresult=service.DoSomething();Assert.That(result,Is.EqualTo("I didn't have to mock the other 2 dependencies!"));}
It really reduces the noise level in tests and lets you focus on the interesting parts of your application. Here’s the code for the container extension: