Tech and Media Labs
This site uses cookies to improve the user experience.

Unit Testing with Dependency Injection Containers

Jakob Jenkov
Last update: 2014-05-24

If you are using a dependency injection container in your application, you can use the container to inject mock objects into your units during unit testing.

Due to how dependency injection affects your design, injecting mocks is already easier, even if you don't use the dependency injection container during your unit tests. Many components can be tested without the use of the dependency injection container, if their dependencies are simple to mock out. However, some more complex components may be easier to test by having them configured by your dependency injection container.

A dependency injection container is usually configured using either code, or some configuration file. During unit testing you would need either a completely different configuration file or code, or you would need a way to modify the existing configuration files or code, from inside your unit tests.

The dependency injection container that I've developed, Butterfly DI Container, enables you to replace factory definitions at runtime. That way, you can use the production configuration as a base during your unit tests, and then just replace the factories of the objects you need to mock out, with mock object factories.

This diagram illustrates the principle of replacing a dependency with a mock object during unit tests:

Testing with Dependency Injections Containers
Testing with Dependency Injections Containers.

Jakob Jenkov

Copyright  Jenkov Aps
Close TOC