Using IoC for Unit Testing

Generally speaking, a DI Container should not be necessary for unit testing because unit testing is all about separating responsibilities.

Consider a class that uses Constructor Injection

public MyClass(IMyDependency dep) { }

In your entire application, it may be that there’s a huge dependency graph hidden behind IMyDependency, but in a unit test, you flatten it all down to a single Test Double.

You can use dynamic mocks like Moq or RhinoMocks to generate the Test Double, but it is not required.

var dep = new Mock<IMyDependency>().Object;
var sut = new MyClass(dep);

In some cases, an auto-mocking container can be nice to have, but you don’t need to use the same DI Container that the production application uses.

Leave a Comment