A stub replaces a dependency with an implementation that returns a pre-programmed response. In a Spring Boot test, it lets the application under test receive predictable values without relying on the dependency’s real behavior. section 3.4
A deliberately limited test context may fail to start because a selected configuration creates beans whose dependencies were not included. Supplying test substitutes satisfies those dependencies without pulling in the real classes and their own dependency graphs. A custom @TestConfiguration can provide stub implementations when a small, manually selected test application is useful. section 3.3.4 section 3.4
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 ...
}
@MockitoBean supplies the missing Gizmo and Widget beans for a test that loads only ThingConfiguration. The Widget substitute is named because bean-name-based autowiring must distinguish it from another Widget. These mocks initially have default behavior; program a response when the test needs a stub rather than merely a bean that satisfies wiring. section 3.4
The distinction is whether the test uses the substitute’s behavior. An unused mock that only allows the context to start is a dummy; a mock programmed to return a specific value is a stub. @TestBean is another way to provide test beans through static factory methods. Use the lightest substitute that supports the behavior being tested. section 3.4 section 3.3.4
Stubs also keep Spring Boot tests independent of many external services and can simulate dependency failures such as timeouts, protocol errors, or invalid data. They support repeatable application tests, but do not make every test a good fit for Spring Boot: narrow code with many conditional branches may be better tested at a smaller scope. section 1.2













