One Last Simplification: Introducing an Injection Tool

Learn to simplify tests using dependency injections.

Passing a mock to a target class using a constructor is one option. It requires a change to the interface and exposes a private detail to another class in the production code. Not a great deal, but we can do better by using a dependency injection (DI) tool like Spring DI and Google Guice.

Dependency injection in Mockito

Since we’re using Mockito, we’ll use its built-in DI capabilities. The DI power in Mockito isn’t as sophisticated as those found in other tools, but most of the time we shouldn’t need anything more.

Using DI in Mockito means following these steps:

  1. Create a mock instance using the @Mock annotation.
  2. Declare a target instance variable annotated with @InjectMocks.
  3. After instantiating the target instance, call MockitoAnnotations.initMocks(this).

Here’s the code:

Get hands-on with 1200+ tech skills courses.