Search⌘ K
AI Features

One Last Simplification: Introducing an Injection Tool

Explore how to apply Mockito’s dependency injection features to simplify your Java unit tests. Understand how @Mock and @InjectMocks work together to inject mocks automatically, reducing boilerplate and improving test design without altering production code.

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 ...