liveBook · Manning

@MockitoBean

As explained in Testing Spring Boot Applications

@MockitoBean is a Spring testing annotation that registers a Mockito mock as a bean, adding or replacing a matching bean in the application context.

@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

How Testing Spring Boot Applications covers it

How deep it goes
Explains annotation-driven replacement, named beans, default values, and stubbing, but does not detail Mockito internals.
Examples
Uses weather-service stubbing, named widget dependencies, and MockMvc requests against a full application context.
What it assumes
Assumes Spring bean dependencies and teaches mock replacement, default values, and stubbing through annotation-driven tests.
What you can do after
Apply it via Spring Boot Tests and Mockito to isolate dependencies, start the context, and verify application behavior.
How it connects
Connects Spring Boot testing with Mockito mocks, stubs, bean autowiring, application contexts, MockMvc, and @TestBean.

Also explained in

Compare how 2 books explain @MockitoBean →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Testing Spring Boot Applications. The section links point to the parts of the book it draws on.