One Last Simplification: Introducing an Injection Tool

Passing a mock to a target class using a constructor is one technique. It requires a change to the interface and exposes a private detail to another class in the production code. Not a great deal, but you can do better by using a dependency injection (DI) tool. You’ll find a handful or more of DI tools out there, including Spring DI and Google Guice.

Because we’re using Mockito, however, we’ll use its built-in DI capabilities. The DI power in Mockito isn’t as sophisticated as you might find in other tools, but most of the time you 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 ...

Get Pragmatic Unit Testing in Java 8 with JUnit now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.