Mockito: Mocking, Stubbing, Verifications, Spy vs Mock
Learn Mockito fundamentals: create mocks and spies, stub behavior with when().thenReturn(), verify interactions, and choose between Spy vs Mock wisely.
Use Mockito to control collaborators in focused tests, then assert the result or state the caller can observe. This guide covers stubbing, meaningful interaction checks, the risks of spies and deep stubs, and when a fake or Testcontainers is a better fit for a database or HTTP boundary. Examples target Mockito 5.24.0, JUnit Jupiter 6.0.1, and Spring Framework 6.2+.
Mockito: Mocking, Stubbing, Verifications, Spy vs Mock
The examples here target Mockito 5.24.0 and JUnit Jupiter 6.0.1 on Java 17 or later. Spring examples use Spring Framework 6.2+ annotations, available with Spring Boot 3.4+. Check the versions in your own build before copying an example: APIs and defaults can change. See the Mockito release notes, JUnit 6 user guide, and Spring’s @MockitoBean reference.
Mockito creates test doubles for collaborators so a test can focus on one class without calling a real database or remote service. Use assertions on the result or externally visible state as the main test contract. Verify an interaction when that call is part of the behavior, such as sending a payment request or publishing an event.
The examples cover common Mockito operations, where spies and deep stubs can mislead a test, and when to use a real dependency instead.
What is Mockito and Why It Matters in Spring Boot
In a Spring MVC slice test, the web layer loads without the application’s full service graph. @MockitoBean can add a mock collaborator to the test context so the controller can be exercised without starting that dependency.
@WebMvcTest(MyController.class)
class MyControllerTest {
@MockitoBean
private MyService myService;
@Autowired
private MockMvc mockMvc;
@Test
void getCustomer_returnsCustomerFromService() throws Exception {
when(myService.findById(1L)).thenReturn(new Customer("Alice", "alice@example.com"));
mockMvc.perform(get("/customers/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Alice"));
}
}
@MockitoBean registers a Mockito mock in the Spring test context and replaces a matching bean when one exists. Spring Boot’s older @MockBean annotation is deprecated starting with Spring Boot 3.4; use the Spring Framework annotation in new code.
When to Use Mockito and When to Choose Something Else
Mockito excels at unit testing isolated classes with external dependencies, particularly controller tests and service tests where you need fine-grained control over what collaborators return.
Mockito is not a substitute for checking a real integration boundary. A mocked repository can test service branching, but it cannot tell you whether a SQL query, transaction, schema migration, or database constraint works. Use a disposable database through Testcontainers when those behaviors matter. Likewise, a mocked HTTP client checks how your code handles a configured response; a local HTTP stub such as WireMock can exercise serialization, headers, status handling, and request construction across the actual client boundary. Keep a smaller number of tests against a real service when behavior specific to that service matters.
For a broader view of unit, integration, and contract-test boundaries, see API testing approaches and Spring Boot slice testing.
How Mocks and Spies Flow Through a Test
The diagram below shows the lifecycle of a mock or spy in a typical test. You create the double, configure its behavior, inject it into the subject under test, exercise the subject, and finally verify that the right calls happened.
graph TD
A["Test Starts"] --> B["Create Mock or Spy"]
B --> C["Stub Behavior<br/>when thenReturn"]
C --> D["Inject into<br/>System Under Test"]
D --> E["Exercise Subject<br/>Call Methods"]
E --> F["Verify Interactions<br/>verify method"]
F --> G["Test Pass or Fail"]
The flow is the same for both mocks and spies, but the semantics differ. A mock starts with all methods returning safe defaults: null, empty collections, zero primitives. A spy wraps a real instance, so its methods execute unless you stub them otherwise.
Failure Scenarios You Will Encounter
Unstubbed Methods Returning Null
Mockito returns null for object return types by default. This means calling an unstubbed method on a mock can produce a NullPointerException if you pass the result directly into code that expects a non-null value.
@Test
void sendingNotification_whenUserIsNull() {
when(userService.findById(1L)).thenReturn(null);
// This throws NullPointerException because getEmail() is called on null
assertThrows(NullPointerException.class, () -> {
notificationService.notifyUser(1L, "Hello");
});
}
The fix is straightforward: stub every method whose return value your code dereferences.
Strict Stubbing Violations
Strict stubbing can report unused stubs and likely argument mismatches. It does not make every unstubbed invocation fail; unstubbed methods usually return Mockito’s default value unless they have a different default answer.
@MockitoSettings(strictness = Strictness.STRICT_STUBS)
class StrictStubbingTest {
@Mock
private OrderRepository orderRepository;
@Test
void placeOrder_shouldConfirmOrder() {
// This stub is unused because the service never calls getOrderCount().
when(orderRepository.getOrderCount()).thenReturn(5);
orderService.placeOrder(new Order());
}
}
With strict stubbing enabled, remove unused setup or correct a stub whose arguments do not match the invocation. Keep stubs close to the behavior under test so the test’s assumptions are visible.
Trade-Off Table: Spy vs Mock vs Real Objects
| Aspect | Mock | Spy | Real Object |
|---|---|---|---|
| Default behavior | Returns Mockito defaults | Delegates to real object | Executes real logic |
| Stubbing | All methods must be stubbed | Only stub what you need | Not applicable |
| Verification | Can verify calls; verify only meaningful behavior | Can verify calls; same coupling risk | Assert on behavior or state |
| Test setup | Controlled return values | Real behavior unless stubbed | Uses actual collaborators |
| Isolation | Complete | Partial (real object still exists) | None |
| Use when | Collaborator is complex or has side effects | You need real behavior for most calls | Real object is simple and deterministic |
| Risk | Tests can become coupled to implementation | Spy may call real external systems | Tests become non-deterministic |
Prefer a real in-memory object or fake when it is simple and deterministic. Use a mock at an external boundary when the response or interaction must be controlled. Spies call real methods by default, so a stub can accidentally perform I/O or trigger side effects. Partial mocks and deep stubs often hide unclear responsibilities or couple tests to the object’s internal call chain; extract a collaborator or test through a clearer boundary first.
Essential Mockito API in Practice
Setting Up Mocks with @MockitoBean
With Spring Framework 6.2 or later, @MockitoBean registers a mock in the application context and replaces a matching bean.
@SpringBootTest
class IntegrationTest {
@MockitoBean
private PaymentGateway paymentGateway;
@Autowired
private OrderService orderService;
@Test
void checkout_successfulPayment() {
when(paymentGateway.process(anyDouble())).thenReturn(true);
Order order = new Order(BigDecimal.valueOf(99.99));
orderService.checkout(order);
assertEquals(OrderStatus.PAID, order.getStatus());
}
}
Stubbing Behavior with when().thenReturn()
The when().thenReturn() chain sets up a stubbed return value for a method call.
// Simple return value
when(userRepository.findById(1L)).thenReturn(Optional.of(new User("Alice")));
// Throwing an exception
when(cache.get("key")).thenThrow(new RuntimeException("Cache unavailable"));
// Sequential returns (last one wins for subsequent calls)
when(counter.increment()).thenReturn(1).thenReturn(2).thenReturn(3);
// doReturn syntax (useful when spying)
doReturn("stubbed").when(spy).getData();
Verifying Interactions with verify()
Verification confirms that a method was called, how many times, and with which arguments.
@Test
void transferFunds_movesMoneyBetweenAccounts() {
Account source = new Account("A123", BigDecimal.valueOf(1000));
Account target = new Account("B456", BigDecimal.ZERO);
transferService.transfer(source, target, BigDecimal.valueOf(250));
verify(accountRepository, times(1)).save(source);
verify(accountRepository, times(1)).save(target);
verify(accountRepository, never()).delete(any());
}
Common verification modifiers:
times(n)— exactly n invocationsnever()— zero invocationsatLeastOnce()— one or more invocationsatMost(n)— at most n invocationstimeout(ms).times(n)— verify within a time window
Matching Arguments with ArgumentMatchers
Argument matchers let you write flexible stubs and verifications that match broad patterns instead of exact values.
// Stub with any() matcher
when(inventory.lookup(anyString())).thenReturn(new Item("SKU-001"));
// Stub with combined matchers
when(reportGenerator.generate(anyLong(), argThat(year -> year > 2020)))
.thenReturn("Report Generated");
// Verify with argument captor
ArgumentCaptor<String> skuCaptor = ArgumentCaptor.forClass(String.class);
verify(inventory).lookup(skuCaptor.capture());
assertTrue(skuCaptor.getValue().startsWith("SKU-"));
Common matchers:
any()— matches any argumentanyString(),anyLong(),anyInt(),anyDouble()— typed anyeq(value)— exact match with type safetyargThat(Predicate<T>)— custom predicate matchingisNull(),isNotNull()— null checkscontains(substring),startsWith(prefix)— string matching
Capturing Arguments with @Captor
ArgumentCaptor lets you grab actual argument values passed during verification for detailed assertions.
class NotificationServiceTest {
@Mock
private EmailSender emailSender;
@InjectMocks
private NotificationService notificationService;
@Captor
private ArgumentCaptor<EmailMessage> messageCaptor;
@Test
void sendWelcomeEmail_hasCorrectSubject() {
notificationService.sendWelcome("alice@example.com", "Alice");
verify(emailSender).send(messageCaptor.capture());
EmailMessage message = messageCaptor.getValue();
assertThat(message.getSubject()).isEqualTo("Welcome, Alice!");
assertThat(message.getRecipient()).isEqualTo("alice@example.com");
}
}
Observability Checklist for Mockito Tests
Use this checklist to make your Mockito tests maintainable and readable.
- Stub every method that returns a non-primitive type and is called by the subject under test
- Use descriptive stub setups that read like documentation:
when(service.getUser(id)).thenReturn(user) - Verify only the interactions that matter for the assertion, not every single call
- Keep stubs and verifications close to the test that uses them, not in setup methods
- Name mocks with the collaborator’s role, not its implementation:
userRepositorynotmockUserDao - Prefer
ArgumentMatchersover captors when simple matching suffices - Use JUnit Jupiter’s
assertThrows()for exception assertions - Check that your test fails for the right reason by temporarily breaking the subject under test
- Keep stubbing strict by default; use leniency only for a specific, justified shared stub
Security Notes for Test Isolation
The JUnit extension creates fresh annotated mocks for each test method by default. Shared mutable fixtures or static mocks can still leak state, so keep setup local and close static-mock scopes.
Avoid resetting mocks as routine cleanup. If a mock’s history needs resetting to make several assertions in one test pass, split the test or create a new mock instead.
Never commit test code that prints sensitive data or logs mock interactions with real credentials. Even in tests, treat user data with the same care you apply in production.
Common Pitfalls and How to Avoid Them
Method Call Order on Mocks
Mockito verifies method calls in the order they were made when you use InOrder.
@Test
void workflow_processesStepsInOrder() {
InOrder inOrder = inOrder(workflowEngine);
workflowEngine.start();
workflowEngine.process();
workflowEngine.complete();
inOrder.verify(workflowEngine).start();
inOrder.verify(workflowEngine).process();
inOrder.verify(workflowEngine).complete();
}
Without InOrder, Mockito verifies each call independently and does not care about sequence.
Final Classes and Methods
Mockito 5 uses the inline mock maker by default, so it can mock final classes and methods. Static and final mocking rely on instrumentation and have constraints; consult the versioned Mockito documentation for the runtime and platform requirements.
Cannot mock/spy com.example.FinalPaymentService
Mocking a final class can be useful around a legacy seam, but it does not make a poor boundary easier to maintain. Prefer testing through a stable interface or introducing a small collaborator when that reduces coupling.
Static Methods
Mockito’s inline mock maker supports scoped static mocking. Use mockStatic() sparingly: static mocks are scoped to the creating thread and can make tests sensitive to implementation details.
@Test
void readingConfig_loadsFromStaticSource() {
try (var mockedConfig = mockStatic(Config.class)) {
mockedConfig.when(Config::getApiKey).thenReturn("test-key-123");
String key = Config.getApiKey();
assertEquals("test-key-123", key);
mockedConfig.verify(Config::getApiKey, times(1));
}
}
Try to keep static mocking local to a narrow test. If tests need to replace a static dependency repeatedly, a small injected interface may give the code a clearer seam.
When NOT to Use
Mockito works well for unit testing isolated classes, but it is not the right tool for every situation. Knowing when to skip Mockito keeps your test suite trustworthy and your tests actually useful.
When You Need Real Database Behavior
Use Mockito to test service decisions with a repository collaborator. Use Testcontainers when the test needs to exercise SQL, migrations, constraints, or transaction behavior against a specific database engine. A practical split is: unit test a service with a fake or mock repository, then run a repository integration test against a disposable instance of the production database engine. A mock proves only the behavior you configure; the database test verifies the boundary.
When Testing the HTTP Client Boundary
Stubbing a method on an HttpClient does not check URL construction, serialization, headers, or response parsing. Use a local HTTP server such as WireMock to test your application’s actual client against controlled status codes, headers, and bodies. Use a real staging service only when its behavior is required and the test can safely manage credentials and data.
When the Class Is Too Simple to Need Mocking
If a class is just a thin wrapper that delegates to one collaborator with no conditional logic, mocking adds noise without value. A test that calls new OrderService(new InMemoryOrderRepository()) and asserts on the result is easier to read than a mock-heavy alternative. Only reach for mocks when the class has branching behavior, multiple collaborators, or side effects you need to verify in isolation.
When the test is relying on deep stubs or partial mocks
Deep stubs such as RETURNS_DEEP_STUBS can make a test depend on a chain of internal calls, so a harmless refactor may break it. Partial mocks execute real code on a spy and can reach files, networks, or other side effects. Prefer a real simple object, a small fake, or an explicit collaborator at the boundary when those make the expected behavior clearer.
Test Failure Scenarios
These examples describe common ways a mock-based test can miss behavior at a real integration boundary.
Unstubbed Methods Returning null Causing NPE
Mockito’s default answer commonly returns null for an unstubbed object-returning method. A test may then fail with a NullPointerException when the subject dereferences that result. The test failure identifies an unstubbed path; it does not prove production data is at fault. Add the behavior needed by the scenario or use a real object at that boundary.
Strict Stubbing Violations Explained
Strict stubbing reports unused stubs and some argument mismatches. It does not report every unstubbed invocation. Remove stale setup or correct the arguments, and use the test failure to inspect what the subject actually called.
Final Class Mocking Issues
Mockito 5 uses the inline mock maker by default. If final or static mocking fails on one machine, compare the Mockito version, JVM, and test configuration rather than adding the obsolete inline artifact by habit.
Static Method Mocking Problems
Static mocks are scoped to the thread that created them and should be closed. Keep them in try-with-resources; do not assume that a static mock affects work on another thread.
Incorrect Argument Matching
Use the narrowest matcher that expresses the test. In Mockito, any() does not match null; use isNull() when null is the intended input. Broad matchers can still make a test accept unintended non-null values, so capture or match the relevant argument when it matters.
Quick Recap Checklist
Use this checklist before marking a Mockito test as complete.
- Use real objects or fakes where they make the behavior clearer; mock collaborators at boundaries
- Stub only behavior the scenario depends on
- Assert on the result or observable state; verify only meaningful interactions
-
ArgumentMatchersused for flexible argument matching -
@Captorused when you need to assert on actual argument values - Strict stubbing passes (no unused stubs) or explicitly made lenient
- Test fails for the right reason when the subject is broken
- No shared mutable state between test methods
- No calls to real external systems from spy objects
- Real objects only used when they are simple, deterministic, and have no I/O
Interview Questions
A Mock creates a pure test double from scratch. All method implementations are replaced with stub implementations that return null, empty collections, or zero primitives by default. A Spy wraps an existing real object and delegates most calls to it unless you explicitly stub a method to return something different. Use mocks for complete isolation from collaborators. Use spies when you want real behavior for most calls but need to stub specific methods or verify certain interactions without replacing the entire object's logic.
@MockitoBean do in Spring testing?@MockitoBean creates a Mockito mock and registers it in the Spring test context, replacing a matching bean. It is the Spring Framework 6.2+ annotation for this use; Spring Boot's older @MockBean is deprecated starting in Boot 3.4.
You use verify() combined with argument matchers. For exact values, pass them directly: verify(service).findById(1L). For flexible matching, use ArgumentMatchers: verify(service).findById(anyLong()) or verify(service).findById(argThat(id -> id > 0)). When you need the actual argument value for detailed assertions, create an ArgumentCaptor, pass it to verify, then call captor.getValue() to retrieve the actual argument after the test runs.
An unstubbed object-returning call may produce null, which can cause a NullPointerException when the subject dereferences it. Stub the behavior required by the test, or use a real object or fake where that makes the scenario more representative. Strict stubbing helps find unused stubs and argument mismatches, but it does not fail every unstubbed invocation.
Mockito 5 uses the inline mock maker by default, which supports final classes and methods. Static mocking is also available through mockStatic() and should be scoped with try-with-resources. These tools can help with legacy seams, but repeated use may point to a dependency that would be easier to test through an injected collaborator.
@InjectMocks work and when should you use it?@InjectMocks tries to inject mocks marked with @Mock into the annotated field. Mockito uses constructor injection first, then setter injection, then field injection. Use it when you want to test a class that has multiple dependencies and would otherwise need to manually instantiate it with all its mocks. However, constructor injection is generally preferred over @InjectMocks because it makes dependencies explicit in the constructor signature and works better with DI containers in production code.
when().thenReturn() and doReturn().when() syntax?On a spy, when(spy.method()).thenReturn(value) calls the real method while setting up the stub. Use doReturn(value).when(spy).method() when that real call would have a side effect or throw. Prefer ordinary when().thenReturn() for mocks because it is easier to read.
Use when().thenThrow() for stubs that throw checked or unchecked exceptions. For example: when(service.findById(1L)).thenThrow(new EntityNotFoundException("User not found")). For spies where you want to avoid calling the real method, use doThrow(): doThrow(new RuntimeException("error")).when(spy).someMethod(). You can also use thenThrow() chained for sequential exceptions on successive calls.
Answer interface used for in Mockito?The Answer interface lets you define custom stub behavior that goes beyond simple return values. You can compute a response based on the actual arguments passed, call real methods on a spy, log arguments for debugging, or implement conditional stubbing. Example: when(mock.getData(anyString())).thenAnswer(invocation -> invocation.getArgument(0) + "-processed"). This is useful when the stub logic depends on runtime values rather than fixed return values.
@MockitoSpyBean differ from @MockitoBean in Spring testing?@MockitoBean replaces a matching bean with a mock. @MockitoSpyBean wraps an existing bean with a spy, so real methods can run unless stubbed. Because spies can trigger real behavior, use them only when that is intentional; an extracted collaborator is often a clearer test seam.
InOrder verification in Mockito?InOrder verifies that method calls happened in a specific sequence, not just that they occurred. Create it with inOrder(mock1, mock2) and then call verify in order: inOrder.verify(mock1).methodA() followed by inOrder.verify(mock1).methodB(). This is useful for testing workflows where order matters, such as a checkout process where save must happen before sendConfirmation. Without InOrder, Mockito verifies each call independently.
void in Mockito?For void methods, use doNothing().when(mock).voidMethod(args) or when(mock, () -> { mock.voidMethod(args); return null; }).thenReturn(null). The simpler syntax is doNothing().when(mock).voidMethod(). If you need the void method to throw an exception, use doThrow(new Exception()).when(mock).voidMethod(). This pattern is necessary because you cannot use when(mock.voidMethod()).then... since void methods return nothing.
lenient() stubbing and when would you use it?lenient() disables strict stubbing checks for a specific stub, allowing it to exist without being invoked during the test. Use it when a stub is set up for optional behavior or when a shared base test class sets up stubs that not every subclass test uses. You can apply it per stub with lenient().when(...), per mock with lenient().doReturn..., or globally with @MockitoSettings(strictness = Strictness.LENIENT). Overusing lenient mode can hide real stubbing issues, so use it sparingly.
Use verify(mock, never()).methodName() to assert that a method was not called at all during the test. This is more expressive than checking a counter or flag manually. You can also combine it with times(0): verify(mock, times(0)).methodName() is equivalent but never() reads more clearly in test intent. For verifying no methods were called on any mock, use verifyNoInteractions(mock1, mock2).
ArgumentMatchers allow stubs and verifications to match arguments using patterns instead of exact values. Common matchers include any(), anyString(), anyLong(), eq(value), argThat(predicate), and contains(). They are useful when you want to stub a method for any argument of a certain type, or when verifying that a method was called with a value meeting a condition. However, avoid overly broad matchers like any() on all arguments as they can mask real bugs by accepting incorrect values.
verify() and verifyNoInteractions()?verify() checks a specific method call on a specific mock: verify(service).findById(1L). verifyNoInteractions() asserts that no method was called on the given mocks at all: verifyNoInteractions(mock1, mock2). Use verifyNoInteractions() when you want to ensure a certain code path did not trigger any collaborator calls, such as when a service should return early from a cache hit without calling the repository.
For testing async code, you can stub the async method to return immediately and verify the callback was invoked. Use when(mock.asyncMethod(any())).thenAnswer(invocation -> { ((Callback) invocation.getArgument(1)).onComplete(result); return null; }). Alternatively, use await() from Awaitility library to wait for async operations to complete in tests, or use Thread.sleep() with verify and timeout() to check that a method was eventually called.
Mockito's mock maker creates the test doubles. Mockito 5 uses the inline mock maker by default, which supports final types and methods, and Mockito can also mock static methods through a scoped API. Change the mock maker only for a documented runtime or platform constraint; consult the Mockito 5 documentation before adding a plugin configuration.
Further Reading
- API testing approaches — Boundaries between unit, integration, and contract tests
- Mockito 5.24.0 API Documentation — Versioned API reference
- Mockito GitHub Repository — Source code, release notes, and issue tracker
- Spring Framework 6.2 @MockitoBean Documentation
- Spring Boot 3.4 @MockBean API — Deprecation details
- Martin Fowler: Test Double — Conceptual foundation for mocks, spies, and other test doubles
- JMockit vs Mockito vs EasyMock — Comparison of Java mocking frameworks
- Testcontainers — For integration tests needing real databases in containers
- WireMock — For stubbing HTTP responses in integration tests
Conclusion
Mockito is useful when a test needs a controlled collaborator at a boundary. Keep behavior assertions at the center, add interaction checks when they express a requirement, and use a real database or HTTP server when the integration itself is what needs checking. The examples above use Mockito 5.24.0, JUnit Jupiter 6.0.1, and Spring Framework 6.2+; confirm your project’s versions before applying them.
Category
Related Posts
Spring Boot Build Tools: Maven & Gradle
Configure Maven and Gradle for Spring Boot projects—plugins, dependency management, packaging JARs and WARs, and build automation essentials.
Embedded Web Servers in Spring Boot: Tomcat, Jetty, Undertow
Configure embedded servers in Spring Boot: compare Tomcat, Jetty, and Undertow, tune thread pools, enable access logs, and switch implementations.
JUnit 5 & Jupiter: Lifecycle, Nested & Parameterized Tests
Learn JUnit Jupiter 5.14.4 lifecycle rules, nested tests, and parameterized inputs, with runnable setup order and practical isolation guidance.