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 the various uses of the standard static mock methods of the Mockito API.

As in other articles focused on the Mockito framework (like Mockito Verify or Mockito When/Then), the MyList class shown below will be used as the collaborator to be mocked in test cases:

public class MyList extends AbstractList<String> {

    @Override
    public String get(int index) {
        return null;
    }

    @Override
    public int size() {
        return 1;
    }
}

2. Simple Mocking

The simplest overloaded variant of the mock method is the one with a single parameter for the class to be mocked:

public static <T> T mock(Class<T> classToMock)

We’ll use this method to mock a class and set an expectation:

MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);

Then we’ll execute a method on the mock:

boolean added = listMock.add(randomAlphabetic(6));

The following code confirms that we invoked the add method on the mock. The invocation returns a value that matches the expectation we set before:

verify(listMock).add(anyString());
assertThat(added).isFalse();

3. Mocking With Mock’s Name

In this section, we’ll cover another variant of the mock method, which is provided with an argument specifying the name of the mock:

public static <T> T mock(Class<T> classToMock, String name)

Generally speaking, the name of a mock has nothing to do with the working code. However, it may be helpful in debugging, as we use the mock’s name to track down verification errors.

To ensure the exception message thrown from an unsuccessful verification includes the provided name of a mock, we’ll use assertThatThrownBy.
In the following code, we’ll create a mock for the MyList class and name it myMock:

MyList listMock = mock(MyList.class, "myMock");

Then we’ll set an expectation on a method of the mock and execute it:

when(listMock.add(anyString())).thenReturn(false);
listMock.add(randomAlphabetic(6));

Next, we’ll call the verification inside the assertThatThrownBy and verify the instance of the exception thrown:

assertThatThrownBy(() -> verify(listMock, times(2)).add(anyString()))
    .isInstanceOf(TooFewActualInvocations.class)

Further, we can also verify the exception’s message that it should contain the information about the mock:

assertThatThrownBy(() -> verify(listMock, times(2)).add(anyString()))
    .isInstanceOf(TooFewActualInvocations.class)
    .hasMessageContaining("myMock.add");

Here’s the thrown exception’s message:

org.mockito.exceptions.verification.TooLittleActualInvocations:
myMock.add(<any>);
Wanted 2 times:
at com.baeldung.mockito.MockitoMockTest
  .whenUsingMockWithName_thenCorrect(MockitoMockTest.java:...)
but was 1 time:
at com.baeldung.mockito.MockitoMockTest
  .whenUsingMockWithName_thenCorrect(MockitoMockTest.java:...)

As we can see, the exception message includes the mock’s name, which will be useful for finding the failure point in case of an unsuccessful verification.

4. Mocking With Answer

Here we’ll demonstrate the use of a mock variant in which we’ll configure the strategy for the mock’s answers to interaction at creation time. This mock method’s signature in the Mockito documentation looks like the following:

public static <T> T mock(Class<T> classToMock, Answer defaultAnswer)

Let’s start with the definition of an implementation of the Answer interface:

class CustomAnswer implements Answer<Boolean> {

    @Override
    public Boolean answer(InvocationOnMock invocation) throws Throwable {
        return false;
    }
}

We’ll use the CustomAnswer class above for the generation of a mock:

MyList listMock = mock(MyList.class, new CustomAnswer());

If we don’t set an expectation on a method, the default answer, configured by the CustomAnswer type, will come into play. In order to prove this, we’ll skip over the expectation setting step and jump to the method execution:

boolean added = listMock.add(randomAlphabetic(6));

The following verification and assertion confirm that the mock method with an Answer argument worked as expected:

verify(listMock).add(anyString());
assertThat(added).isFalse();

5. Mocking With MockSettings

The final mock method we’ll cover in this article is the variant with a parameter of the MockSettings type. We use this overloaded method to provide a non-standard mock.

There are several custom settings supported by methods of the MockSettings interface, such as registering a listener for method invocations on the current mock with invocationListeners, configuring serialization with serializable, specifying the instance to spy on with spiedInstance, configuring Mockito to attempt to use a constructor when instantiating a mock with useConstructor, etc.

For convenience, we’ll reuse the CustomAnswer class introduced in the previous section to create a MockSettings implementation that defines a default answer.

A MockSettings object is instantiated by a factory method:

MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());

We’ll use that setting object in the creation of a new mock:

MyList listMock = mock(MyList.class, customSettings);

Similar to the preceding section, we’ll invoke the add method of a MyList instance, and verify that the mock method with a MockSettings argument works as expected:

boolean added = listMock.add(randomAlphabetic(6));

verify(listMock).add(anyString());
assertThat(added).isFalse();

6. Conclusion

In this article, we covered the mock method of Mockito in detail.

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.
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