Sub topic 6
Replacing beans with mocks in a Spring context
This chapter assumes you can write a JUnit 5 test, know what a Spring bean is, and have used Mockito's when(...).thenReturn(...) in a plain unit test. Here you will use the same mocking ideas inside a Spring context.
Why replace a bean
A test that loads a Spring context wires real beans together. Sometimes you want one of them to be fake. A service might call a payment gateway, send email, or read a slow database. Replacing that one bean with a Mockito mock keeps the test fast and deterministic, and it lets you check how other beans interact with it.
In a plain unit test, @Mock creates the mock and @InjectMocks places it in the object under test. Spring is not involved. In a Spring test, the mock must be registered in the application context, so that every bean that depends on it receives the mock.
@MockitoBean and @MockBean
@MockitoBean puts a Mockito mock in the context. If a bean of that type already exists, the mock replaces it. If none exists, the mock is added.
- In Spring Boot 3.4 and later (Spring Framework 6.2), use
@MockitoBean. - In earlier versions, use
@MockBean. It behaves the same way for most tests. It is deprecated in newer versions.
@SpringBootTest
class GreetingServiceIntegrationTest {
@MockitoBean
GreetingRepository repository;
@Autowired
GreetingService service;
@Test
void usesTheMockedRepository() {
when(repository.findByName("Ada"))
.thenReturn(Optional.of(new Greeting("Ada", "Hello, Ada")));
assertThat(service.greetingFor("Ada")).isEqualTo("Hello, Ada");
verify(repository).findByName("Ada");
}
}The real GreetingService is created by Spring, and it receives the mock repository through constructor injection. Mockito mocks return empty or default values (null, 0, Optional.empty() for Optional) until you stub them.
Mocks are reset after each test method, so stubbing in one test does not leak into the next.
@MockitoSpyBean
Sometimes you want the real bean but need to verify calls or stub one method. @MockitoSpyBean wraps the existing bean in a Mockito spy. (The older name is @SpyBean.)
@SpringBootTest
class GreetingAuditTest {
@MockitoSpyBean
GreetingService service;
@Test
void callsRealMethod() {
service.greetingFor("Ada");
verify(service).greetingFor("Ada");
}
}Where the mock lives
Common errors
- Mock bean changes the context cache key. A context with different mock beans is a different context. Each unique combination is built and cached separately, so scattering different
@MockitoBeandeclarations across many test classes slows the suite. Chapter 14 covers the cache. - Using it in a unit test.
@MockitoBeandoes nothing without a Spring context. In a test with@ExtendWith(MockitoExtension.class), use@Mock. - Mocking too much. If a test mocks every collaborator, it only checks that you called mocks. Mock the boundaries (network, database, clock), not your own logic.
- Forgetting to stub. An unstubbed mock returns defaults, so a failure may show up as a
nullor an empty result far from the cause.
Exercise
Exercise
A @SpringBootTest class declares @MockitoBean GreetingRepository repository. Another test class in the same suite declares no mock but uses the same configuration. Will the two classes share a cached application context, and why?
Show answer
No. The set of mock beans is part of the context cache key, so the class with the mock gets its own context and the other class gets a separate one. Both contexts are built and cached independently.