Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll discuss the well-known Mockito annotations @InjectMocks, @Mock, @Spy and understand how they work together in multiple-level injection scenarios. We’ll talk about important testing concepts and learn how to make a proper test configuration.

2. Multiple-Level Injection Concept

The multiple-level injection is a powerful concept, but it can be dangerous when misused. Let’s review important theoretical concepts before moving on to implementation.

2.1. Unit Test Concept

By definition, a unit test is a test that covers one unit of source code. In the Java world, we can talk about the unit test as a test that covers some specific class – service, repository, utils, etc.

When testing a class, we want to test its business logic only, and not the behavior of its dependencies. To deal with dependencies, for example, to mock them, or to verify their usage, we usually use a mocking framework – Mockito. It has been designed to extend existing test engines (JUnit, TestNG) and helps to build unit tests for a class with multiple dependencies properly.

2.2. @Spy Concept

Spy is one of the essential pillars of Mockito that helps to work with dependencies effectively.

A Mock is a complete stub that performs no action when methods are called and doesn’t reach the actual object. On the contrary, Spy delegates all calls to the real object methods by default. And when specified, the spy method can behave as a mock with all its features.

We need to set up the spy object with the necessary dependencies due to its default behavior as a real object. Mockito tries to inject dependencies implicitly to the spy object. However, we can set dependencies explicitly when required.

2.3. Multiple-Level Injection Risks

Multiple-level injection in Mockito refers to the scenario where a tested class requires a spy, and this spy depends on specific mocks for injection, creating a nested injection structure.

In some scenarios, we might face a need for multiple-level mocking. For example, we’re testing some ServiceA, that depends on some complex MapperA, and MapperA depends on a different ServiceB. Generally, it will be easier to make MapperA a spy and inject ServiceB as a mock. However, such an approach breaks a unit test concept. When we need to cover more than one service in a test, we should rather stick to complete integration tests.

If we face a need for multiple-level injection too often, it can be a sign of an incorrect testing approach or complex code design, that should be refactored.

3. Setting Up a Sample Scenario

Before we move on to test cases, let’s define sample code to show how we can use Mockito to test our codebase.

We’ll work with the library concept, where we have a main Book entity, that is being processed by multiple services. The most important takeaway here is the dependencies between classes.

The entry point for processing is BookStorageService, that intended to store information about taken/given books and verify book state via BookControlService:

public class BookStorageService {
    private BookControlService bookControlService;
    private final List<Book> availableBooks;
}

BookControlService on the other hand depends on two more classes, StatisticService and RepairService that should calculate the amount of processed books and check if the book should be repaired:

public class BookControlService {
    private StatisticService statisticService;
    private RepairService repairService;
}

4. Dive Deep With @InjectMocks Annotation

When we think about injecting one Mockito-managed class into another, @InjectMocks annotation looks like the most intuitive mechanism. However, its capabilities are limited. The documentation highlights that Mockito should not be considered a dependency injection framework. It’s not designed to handle complex injection for networks of objects.

Also, Mockito won’t report any injection failure. In other words, when Mockito can’t inject a mock into the field, the field will remain null. Thus we’ll end up with multiple NullPointerExceptions (NPE) in case of incorrect test class setup.

@InjectMocks behaves differently in the different configurations, and not every setup will work in the desired way. Let’s review the features of annotation usage in detail.

4.1. @InjectMocks and @Spy Not Working Configuration

It might be intuitive to use multiple @InjectMocks annotations in one class:

public class MultipleInjectMockDoestWorkTest {
    @InjectMocks
    private BookStorageService bookStorageService;
    @Spy
    @InjectMocks
    private BookControlService bookControlService;
    @Mock
    private StatisticService statisticService;
}

Such configuration is intended to inject statisticService mock into bookControlService spy and inject bookContorlService into bookStorageService. However, such a configuration doesn’t work and causes NPE in the newer Mockito versions.

Under the hood, the current version of the framework (5.10.0) collects all annotated objects into two collections. The first collection is for mock-dependent fields annotated with @InjectMocks (bookStorageService and bookControlService).

The second collection is for all entities candidates for injection, which are all mocks and eligible spies. However, fields marked as @Spy and @InjectMock at the same time are never considered candidates for injection. As a result, Mockito won’t know that bookControlService should be injected into bookStorageService.

Another issue with the configuration above is conceptual. With @InjectMocks annotation we’re targeting two classes (BookStorageService and BookControlService) to be tested in the class, which is against the unit test approach.

4.2. @InjectMocks and @Spy Working Configuration

At the same time, there is no restriction on the usage of @Spy and @InjectMocks together, as soon as there is only one @InjectMocks annotation in the class:

@Spy
@InjectMocks
private BookControlService bookControlService;
@Mock
private StatisticService statisticService;
@Spy
private RepairService repairService;

With this configuration, we have a properly built and testable hierarchy:

@Test
void whenOneInjectMockWithSpy_thenHierarchySuccessfullyInitialized(){
    Book book = new Book("Some name", "Some author", 355, ZonedDateTime.now());
    bookControlService.returnBook(book);

    Assertions.assertNull(book.getReturnDate());
    Mockito.verify(statisticService).calculateAdded();
    Mockito.verify(repairService).shouldRepair(book);
}

5. Multiple-Level Injection via @InjectMocks and Manual Spy

One of the options to resolve multiple-level injection is to manually instantiate a spy object before Mockito initialization. As we’ve already discussed, Mockito cannot inject all dependencies into the field, which is annotated with both @Spy and @InjectMocks. However, the framework can inject dependencies to an object that is annotated with @InjectMocks only, even if this object is a spy.

We can use @ExtendWith(MockitoExtension.class) on the class level and initialize spy in the field:

@InjectMocks
private BookControlService bookControlService = Mockito.spy(BookControlService.class);

Or we can use MockitoAnnotations.openMocks(this) and initialize spy in the @BeforeEach method:

@BeforeEach
public void openMocks() {
    bookControlService = Mockito.spy(BookControlService.class);
    closeable = MockitoAnnotations.openMocks(this);
}

In both cases, a spy should be created before Mockito initialization.

With the setups above, Mockito handles @InjectMocks on the manually created spy and injects all needed mocks:

@InjectMocks
private BookStorageService bookStorageService;
@InjectMocks
private BookControlService bookControlService;
@Mock
private StatisticService statisticService;
@Mock
private RepairService repairService;

The test is successfully executed:

@Test
void whenSpyIsManuallyCreated_thenInjectMocksWorks() {
    Book book = new Book("Some name", "Some author", 355);
    bookStorageService.returnBook(book);

    Assertions.assertEquals(1, bookStorageService.getAvailableBooks().size());
    Mockito.verify(bookControlService).returnBook(book);
    Mockito.verify(statisticService).calculateAdded();
    Mockito.verify(repairService).shouldRepair(book);
}

6. Multiple-level Injection via Reflection

Another possible approach to handling complex test setups is by manually creating the required spy object and then injecting it into the object under test. Leveraging reflection mechanisms, we can update Mockito-created objects with the needed spy.

In the following example, rather than annotating BookControlService with @InjectMocks, we’ve manually configured everything. To ensure the Mockito-created mocks are available during spy initialization, the Mockito context must be initialized first. Otherwise, NullPointerExceptions may occur wherever mocks are utilized.

Once the BookControlService spy is configured with all mocks, we inject it to BookStorageService via reflection:

@InjectMocks
private BookStorageService bookStorageService;
@Mock
private StatisticService statisticService;
@Mock
private RepairService repairService;
private BookControlService bookControlService;

@BeforeEach
public void openMocks() throws Exception {
    bookControlService = Mockito.spy(new BookControlService(statisticService, repairService));
    injectSpyToTestedMock(bookStorageService, bookControlService);
}

private void injectSpyToTestedMock(BookStorageService bookStorageService, BookControlService bookControlService) 
  throws NoSuchFieldException, IllegalAccessException { 
    Field bookControlServiceField = BookStorageService.class.getDeclaredField("bookControlService"); 
    bookControlServiceField.setAccessible(true); 
    bookControlServiceField.set(bookStorageService, bookControlService); 
}

With such a configuration, we can verify the behavior of repairService and bookControlService.

7. Conclusion

In this article, we’ve reviewed the important unit-test concepts and learned how to work with @InjectMocks, @Spy, and @Mock annotations to perform complex multiple-level injections. We’ve discovered how spy can be configured manually and how it can be injected into the tested object.

As always, the complete examples are available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
4 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.