@MockitoBean is a Spring testing annotation that adds a Mockito mock to the application context or replaces a matching production bean. It lets a test declare only the dependency that should behave differently while Spring Boot manages the surrounding context. section 1.4 section 2.6
Use @MockitoBean to:
- Decouple tests from external services by programming predictable return values. section 2.6
- Satisfy dependencies that are needed for context startup but are irrelevant to the test. section 3.4
- Select a named bean when multiple beans share the same type. section 3.4
- Use default mock values when behavior is irrelevant, or configure a canned response when the test exercises the dependency. section 3.4
Replace and stub a service
@MockitoBean private WeatherService weatherService; @Test void getWeather() { when(weatherService.getCurrentWeather(anyDouble(), anyDouble())) .thenReturn(new WeatherData(22.6, 0, 1)); // exercise the API and assert its response } section 2.6
Listing 3.13 Providing beans with @MockitoBean
@SpringBootTest(classes = { ThingConfiguration.class }) #1
class CustomClassesTests {
@MockitoBean #2
Gizmo gizmo;
@MockitoBean(name = "blueWidget") #3
Widget blueWidget;
// ... your test code ...
}
Shows a full-context test supplying unnamed and named Mockito beans, including a named replacement for one of several beans of the same type. section 3.4
For a full Spring Boot test, combine @MockitoBean with @SpringBootTest and access the mock through the injected field. When a real test implementation is preferable, @TestBean can provide one through a factory method instead. section 1.4 section 3.4

