- Java Unit Testing
- A Simple Unit Test
- Assert Methods
- Testing for Exceptions
- Stub, Mock and Proxy Testing
- Subclass Mock Objects
- Mock Testing isn't Always Enough
- IO Testing
- Servlet Unit Testing
- Unit Testing with Dependency Injection Containers
- Database Unit Testing - Rollback Transactions
- Database Unit Testing - CRUD Testing
- Database Unit Testing - Test Data Creation
- Running Unit Tests With Ant
- Running Unit Tests With Maven
- Running Unit Tests Inside IntelliJ IDEA
- Code Coverage
- Design for Testability
- Test First Development
Unit Testing with Dependency Injection Containers
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.|