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 – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Overview

Mockito is one of the most popular testing libraries in the Java ecosystem. We use it to isolate units of code, replace external dependencies, and write fast and focused tests. However, Mockito is often overused, and one of the most common misuses is mocking Java collections such as List, Set, or Map.

At first glance, mocking collections feels harmless. Mockito allows it, the tests compile, and everything looks fine. Over time, though, this practice leads to brittle tests, unrealistic behavior, and reduced confidence. On newer Java versions, it can even cause test failures.

In this tutorial, we’ll explore why mocking collections is problematic and what we should do instead.

2. Collections Are Not Our Dependencies

Before mocking anything, we should decide whether it is truly a dependency. Dependencies are usually external, slow, or non-deterministic, such as databases, REST clients, message brokers, or system clocks. Java collections do not fall into this category. They are part of the core JDK, deterministic, lightweight, and extensively tested.

When we mock a collection, we are not isolating our code from external behavior. Instead, we are replacing well-defined Java behavior with artificial stubs. This increases complexity without providing meaningful isolation.

3. Example Code

Let’s start with a simple service class that uses a collection internally:

public class UserService {
    private final List<String> users;

    public UserService(List<String> users) {
        this.users = users;
    }

    public boolean hasUsers() {
        return !users.isEmpty();
    }

    public String getFirstUser() {
        if (users.isEmpty()) {
            return null;
        }
        return users.get(0);
    }
}

The List here is purely a data structure. It does not represent an external collaborator or a side-effecting dependency.

4. Mocking a Collection

A real collection maintains an internal state. When we add an element, its size changes automatically. A mocked collection has no such behavior unless we explicitly define it. This difference often leads to tests that pass even though they do not reflect real runtime behavior.

The situation becomes even more problematic on newer Java versions.

The following test intentionally demonstrates the problems with mocking collections. On modern Java versions, this test may fail before it even runs:

@Test
void shouldFailToMockCollection_onModernJavaVersions() {
    // This line may fail on Java 21+ due to JVM restrictions
    List<String> users = mock(List.class);

    UserService userService = new UserService(users);

    // The test may never reach this point
    userService.hasUsers();
}

On Java 21 and later, Mockito may throw an exception similar to:

Mockito cannot mock this class: interface java.util.List
Could not modify all classes [Iterable, SequencedCollection, Collection, List]

This failure is not caused by incorrect test logic. It is the result of stricter JVM rules around runtime instrumentation of core JDK types.

5. Tests Become Over-Specified and Fragile

Even when mocking collections is technically possible, tests tend to become tightly coupled to implementation details. They often verify how many times isEmpty() or get(0) is called rather than focusing on observable behavior. Small internal refactorings can break tests even when functionality remains unchanged.

Good unit tests should protect refactoring, not resist it.

6. Using a Real Collection Instead

Using a real collection avoids all of these problems:

@Test
void givenList_whenRealCollectionIsUsed_thenShouldReturnFirstUser() {
    List<String> users = new ArrayList<>();
    users.add("Joey");

    UserService userService = new UserService(users);

    assertTrue(userService.hasUsers());
    assertEquals("Joey", userService.getFirstUser());
}

This test works consistently across Java versions, requires no stubbing, and accurately mirrors production behavior.

Edge cases are also easier to test with real collections:

@Test
void givenEmptyList_whenUserListIsEmpty_thenShouldReturnNull() {
    List<String> users = new ArrayList<>();

    UserService userService = new UserService(users);

    assertNull(userService.getFirstUser());
}

This test clearly documents the expected behavior without relying on Mockito.

The need to mock collections often signals deeper design problems, such as overly coupled logic or unclear responsibilities. Using real collections in tests tends to expose these issues and encourages cleaner APIs and better separation of concerns.

7. Conclusion

In this article, we saw that mocking Java collections is rarely a good idea. It leads to brittle tests, unrealistic behavior, and unnecessary coupling to implementation details. On modern Java versions, it can even result in runtime failures due to stricter JVM constraints.

Mockito remains a powerful and valuable tool when used correctly. It should mock true collaborators and external dependencies, not core data structures. By using real collections in tests, we write code that is clearer, safer, and more resilient to change.

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.

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

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

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

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)