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 – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

In this tutorial, we’ll illustrate how to make the most out of spies in Mockito.

We’ll talk about the @Spy annotation and how to stub a spy. Finally, we’ll go into the difference between Mock and Spy.

Of course, for more Mockito goodness, have a look at the series here.

Further reading:

Mockito Verify Cookbook

<strong>Mockito Verify</strong> examples, usage and best practices.

Injecting Mockito Mocks into Spring Beans

This article will show how to use dependency injection to insert Mockito mocks into Spring Beans for unit testing.

Mockito's Mock Methods

This tutorial illustrates various uses of the standard static mock methods of the Mockito API.

2. Simple Spy Example

Let’s start with a simple example of how to use a spy.

Simply put, the API is Mockito.spy() to spy on a real object.

This will allow us to call all the normal methods of the object while still tracking every interaction, just as we would with a mock.

Now let’s do a quick example where we’ll spy on an existing ArrayList object:

@Test
void givenUsingSpyMethod_whenSpyingOnList_thenCorrect() {
    List<String> list = new ArrayList<String>();
    List<String> spyList = spy(list);

    spyList.add("one");
    spyList.add("two");

    verify(spyList).add("one");
    verify(spyList).add("two");

    assertThat(spyList).hasSize(2);
}

Note how the real method add() is actually called and how the size of spyList becomes 2.

3. The @Spy Annotation

Next, let’s see how to use the @Spy annotation. We can use the @Spy annotation instead of spy():

@Spy
List<String> spyList = new ArrayList<String>();

@Test
void givenUsingSpyAnnotation_whenSpyingOnList_thenCorrect() {
    spyList.add("one");
    spyList.add("two");

    verify(spyList).add("one");
    verify(spyList).add("two");

    assertThat(aSpyList).hasSize(2);
}

To enable Mockito annotations (such as @Spy, @Mock, … ), we need to use @ExtendWith(MockitoExtension.class) that initializes mocks and handles strict stubbings.

4. Stubbing a Spy

Now let’s see how to stub a Spy. We can configure/override the behavior of a method using the same syntax we would use with a mock.

Here we’ll use doReturn() to override the size() method:

@Test
void givenASpy_whenStubbingTheBehaviour_thenCorrect() {
    List<String> list = new ArrayList<String>();
    List<String> spyList = spy(list);

    assertEquals(0, spyList.size());

    doReturn(100).when(spyList).size();
    assertThat(spyList).hasSize(100);
}

5. Mock vs Spy in Mockito

Let’s discuss the difference between Mock and Spy in Mockito. We won’t examine the theoretical differences between the two concepts, just how they differ within Mockito itself.

When Mockito creates a mock, it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it.

On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance; the only difference is that it will also be instrumented to track all the interactions with it.

Here we’ll create a mock of the ArrayList class:

@Test
void whenCreateMock_thenCreated() {
    List mockedList = mock(ArrayList.class);

    mockedList.add("one");
    verify(mockedList).add("one");

    assertThat(mockedList).hasSize(0);
}

As we can see, adding an element into the mocked list doesn’t actually add anything; it just calls the method with no other side effects.

A spy, on the other hand, will behave differently; it will actually call the real implementation of the add method and add the element to the underlying list:

@Test
void whenCreateSpy_thenCreate() {
    List spyList = Mockito.spy(new ArrayList());

    spyList.add("one");
    Mockito.verify(spyList).add("one");

    assertThat(spyList).hasSize(1);
}

6. Understanding the Mockito NotAMockException

In this final section, we’ll learn about the Mockito NotAMockException. This exception is one of the common exceptions we will likely encounter when misusing mocks or spies.

Let’s start by understanding the circumstances in which this exception can occur:

List<String> list = new ArrayList<String>();
doReturn(100).when(list).size();

When we run this code snippet, we’ll get the following error:

org.mockito.exceptions.misusing.NotAMockException: 
Argument passed to when() is not a mock!
Example of correct stubbing:
    doThrow(new RuntimeException()).when(mock).someMethod();

Thankfully, it is quite clear from the Mockito error message what the problem is here. In our example, the list object is not a mock. The Mockito when() method expects a mock or spy object as the argument.

As we can also see, the Exception message even describes what a correct invocation should look like. Now that we have a better understanding of what the problem is, let’s fix it by following the recommendation:

final List<String> spyList = spy(new ArrayList<>());
assertThatNoException().isThrownBy(() -> doReturn(100).when(spyList).size());

Our example now behaves as expected, and we no longer see the Mockito NotAMockException.

7. Conclusion

In this brief article, we discussed the most useful examples of using Mockito spies.

We learned how to create a spy, use the @Spy annotation, stub a spy, and finally, the difference between Mock and Spy.

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.

This is a Maven project, so it should be easy to import and run as it is.

Finally, for more Mockito goodness, have a look at the series here.

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 – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW