All Posts assertfail

View the Blog on GitHub wallymathieu

Unit testing using Moq and Unity Container

29 Sep 2010

I have had troubles writing unit tests for classes with a lot of dependencies. The reason for this is that the initialization of the state for my test code would look like:
public void Setup()
   stub1 = new Mock();

  stub20 = new Mock();
  mock = new Mock();
…// Setup mock and stub behavior
  classToTest = new TypeOfClass( /a lot of code/);

This isn’t very maintainable. How do we make this easier to maintain? I’ve introduced a helper class that initializes most of the interfaces to stubs of the form Mock. Then these stubs can be added to Unity. Thus the setup will be reduced to:

<div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">[Setup]</div>

public void Setup()
  container = new UnityContainerTestHelper();
  container.RegisterStubs();//Registers a lot of interfaces using Moq 
...// Setup mock and stub behavior
  classToTest = container.Resolve();
The main thing here is that I'm the dependency injection container do the work. People have told me that dependency injection would help when testing. It does, but I've not seen examples of the use of a dependency injection container. If you have better ideas how this should be done, please post comments.


  • dependency_injection
  • c#
  • moq
  • unit-test
  • unity
  • Comments or errors? Fork post and do a pull request on github