Sub topic 6
Replacing beans with mocks in a Spring context
This chapter assumes you can write a Mockito unit test and know what a Spring bean is. It also assumes you have seen @SpringBootTest and @WebMvcTest. The chapter covers how to swap a real bean for a Mockito mock inside a running test context, and the errors this causes.
Why replace a bean
A Spring test context contains real beans wired together. Some of those beans are expensive or unsafe in a test: an HTTP client for a payment provider, a mail sender, a message publisher. Other beans sit outside the slice you are testing. A @WebMvcTest loads controllers but not services, so a controller's GreetingService dependency has nothing to inject.
In both cases you want the context to contain a mock in place of the real bean. Everything else stays wired normally. Spring Framework provides annotations for this, and Spring Boot's test support builds on them.
@MockitoBean and @MockBean
@MockitoBean comes from Spring Framework 6.2, so it is available in Spring Boot 3.4 and later. It replaces @MockBean from Spring Boot, which was deprecated in 3.4 and removed in Spring Boot 4.0. The behavior is the same for the cases in this chapter. Use @MockitoBean on new code, and @MockBean only if you are stuck on an older Boot version.
| Purpose | Spring Boot 3.4 and later | Older Spring Boot |
|---|---|---|
| Replace a bean with a mock | `@MockitoBean` | `@MockBean` |
| Wrap the real bean in a spy | `@MockitoSpyBean` | `@SpyBean` |
Do not confuse these with @Mock from Mockito. @Mock creates an object that Spring knows nothing about, and it only works with MockitoExtension or MockitoAnnotations. @MockitoBean creates a mock and registers it in the ApplicationContext, so every bean that depends on that type receives the mock.
A worked example
Suppose an OrderService saves orders and notifies customers through a NotificationClient. The real client calls an external API.
public interface NotificationClient {
void send(String recipient, String message);
}import org.springframework.stereotype.Service;
@Service
public class OrderService {
private final NotificationClient notifications;
public OrderService(NotificationClient notifications) {
this.notifications = notifications;
}
public String placeOrder(String customer, String item) {
String confirmation = "Order for " + item + " accepted";
notifications.send(customer, confirmation);
return confirmation;
}
}The test loads the full context, but the mock takes the place of the client:
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
@SpringBootTest
class OrderServiceIntegrationTest {
@Autowired
OrderService orderService;
@MockitoBean
NotificationClient notificationClient;
@Test
void placingAnOrderNotifiesTheCustomer() {
String result = orderService.placeOrder("[email protected]", "keyboard");
assertThat(result).isEqualTo("Order for keyboard accepted");
verify(notificationClient)
.send("[email protected]", "Order for keyboard accepted");
}
}The service is a real bean, wired by Spring. Its NotificationClient is the mock, because the annotation replaced the bean definition before the context finished starting. The test needs no stubbing: send returns void, so the mock does nothing by default, and verify checks that it was called.
What happens inside the context
Spring processes the @MockitoBean field while it builds the context for the test class. It looks for an existing bean of the field's type. If one exists, it replaces that bean definition with a Mockito mock. If none exists, it registers a new mock bean.
That second rule matters. A mock that "just works" can hide a missing production bean, because the test passes even when your real configuration never defines the bean.
Stubbing and verifying
Mocks created by @MockitoBean are ordinary Mockito mocks, so the usual tools apply. Unstubbed methods return defaults: null for objects, 0 for numbers, an empty Optional, and empty collections.
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
@SpringBootTest
class OrderServiceFailureTest {
@Autowired
OrderService orderService;
@MockitoBean
NotificationClient notificationClient;
@Test
void capturesTheMessageSent() {
orderService.placeOrder("[email protected]", "monitor");
ArgumentCaptor<String> message = ArgumentCaptor.forClass(String.class);
verify(notificationClient).send(anyString(), message.capture());
assertThat(message.getValue()).contains("monitor");
}
}given(...) from BDDMockito is a readable alias for when(...). Use whichever your team already uses.
Reset and lifecycle
Mockito resets each @MockitoBean mock after every test method. Stubbing and recorded invocations from one test do not leak into the next, even though the context is shared. You do not need Mockito.reset(...) in an @AfterEach method.
Spying on a real bean
A mock replaces behavior entirely. A spy wraps the real bean and lets you stub or verify selected calls. Use @MockitoSpyBean when you want the real logic to run and only need to observe it, or to override one method.
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
@SpringBootTest
class OrderServiceSpyTest {
@Autowired
OrderService orderService;
@MockitoSpyBean
OrderService spiedOrderService;
@Test
void placeOrderIsCalledOnce() {
spiedOrderService.placeOrder("[email protected]", "mouse");
verify(spiedOrderService).placeOrder("[email protected]", "mouse");
}
}A spy needs an existing bean to wrap. If there is none, context startup fails. Reach for a spy rarely. If you find yourself stubbing half the methods of a spy, a plain mock or a real collaborator is usually clearer.
Choosing between mocks, fakes, and test configuration
@MockitoBean is the shortest way to replace a bean, but not the only one. A @TestConfiguration class can define a replacement bean explicitly. That fits when you want a hand-written fake with real, simple behavior, such as an in-memory notification recorder.
| Approach | Best for | Cost |
|---|---|---|
| `@MockitoBean` | Stubbing responses, verifying calls on one test class | Changes the context cache key |
| `@TestConfiguration` with a fake | Shared fake behavior used by many tests | More code, but reusable |
| Real bean | Cheap, deterministic collaborators | Slower tests if the bean is heavy |
Context caching and mocks
Spring caches an application context and reuses it across test classes with the same configuration. The set of bean overrides is part of the cache key. Two classes with different @MockitoBean declarations get different contexts, and each one starts separately.
This makes the choice of mocks a performance decision. If ten test classes each mock a different combination of beans, the suite builds ten contexts. Two ways to limit this:
- Declare the same mocks in a shared abstract base class, or on a common set of test classes, so they share one cached context.
- Mock only the beans that must be replaced. Every extra mock splits the cache.
Common errors
NoSuchBeanDefinitionExceptionin a@WebMvcTest. The controller needs a service, and the slice does not load services. Add a@MockitoBeanfield for each missing dependency.NullPointerExceptionfrom a mock's return value. An unstubbed method that returns an object gives younull. Stub the call, or check the real return type.- Using
@Mockin a Spring test. The object is created but never registered in the context, so the real bean (or an error) is injected instead. Use@MockitoBeanwhenever Spring must see the mock. - Two beans of the same type. If the context has several candidates, the replacement is ambiguous. Specify the bean by name with the annotation's
nameattribute. - Mocking the class under test. In
@SpringBootTest, mockingOrderServiceand then testingOrderServicetests nothing. Mock the collaborators, not the subject. - Missing production wiring. Because a missing bean is created as a mock, the test passes while the application fails to start. Keep at least one test that loads the real context with no mocks for that type.
Summary of the model
@MockitoBean edits the context's bean definitions before startup, so every dependent bean receives the mock. Mocks are reset after each test. Each distinct set of overrides produces a distinct cached context, so declare them deliberately.
Exercise
A test class annotated with @SpringBootTest declares @MockitoBean NotificationClient client;, and the application has no NotificationClient bean defined in production configuration. What happens when the test runs, and why can this be a problem?
Show answer
The context starts without error, because @MockitoBean registers a new mock bean when no bean of that type exists. Tests that depend on the client pass. The problem is that the real application would fail at startup (or lack the feature) because the bean is never defined, and the mock hides it. Keep a test that loads the real context without that mock to catch missing wiring.
Exercise
Two test classes both use @SpringBootTest. One declares @MockitoBean NotificationClient, the other declares @MockitoBean NotificationClient and @MockitoBean PaymentClient. How many application contexts does Spring start for these two classes, and how could you reduce that?
Show answer
Two contexts, because the sets of bean overrides differ and the overrides are part of the context cache key. To reduce it, declare the same set of mocks in both classes (for example, in a shared base class) so they reuse one cached context, or drop the PaymentClient mock if the second test does not need it.