Follow @RoyOsherove on Twitter

Pros and Cons and of using an Auto Mocking container in your tests

In regards to my post about injecting mocks and stubs using a container in your tests, Dave asks in the comments: Why would you want to do this in the first place?

Here are the things I can think about right now (pros and cons). I'd love to hear your thoughts.

Pros for using a container in your tests:

  • Can lead to easier test maintainability. You can add new dependencies to object under test without worrying about existing tests that use that object, since those dependencies will usually be automatically stubbed out as part of the object creation process
  • Allows easier focus on testing interaction. When you have a class that has 3+ dependencies, you'd usually want to have no more than one mock against which you'll test the interaction of the class, while the rest would be stubs.  Since everything is getting stubbed by default, all you need to worry about when writing the test is about the mock's expected interaction and perhaps setting one of the stubs to run using a specific behavior.  In any case, writing the boilerplate stubbing code for all the dependencies is spared from you, something which I have struggled with before

Cons of using a container:

  • It could make the test a little less readable in terms of understanding what gets injected and what the actual dependencies are. Assuming the reader already knows how to use containers, there is still a very clear separation between setting up the container's mocks and stubs and looks at where they are being used. By design , a container's work is hidden under an abstraction layer, which also makes the test reader not see how the mocks and stubs fit together inside the object under test.

I'm a wuss

Testing XML serialization attributes