Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

Partner – LambdaTest – NPI (cat= Testing)
announcement - icon

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat = Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

eBook – Mockito – NPI (tag=Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

>> Download the eBook

eBook Jackson – NPI EA – 3 (cat = Jackson)
4 Comments
Oldest
Newest
Inline Feedbacks
View all comments