@TestBean supplies a test-specific bean to a Spring application context without using Mockito. It constructs the replacement through a static factory method, making it useful when a test needs a controlled object rather than a Mockito mock. section 3.4
By default, Spring searches for a static factory method whose name matches the annotated field. Set methodName when the factory has a descriptive or shared name, or reference an external static method with a fully qualified name. Factory code can construct objects directly, pass null where supported, or create subclasses that avoid production dependencies. section 3.4
Supplying Gizmo and Widget beans
@SpringBootTest(classes = { ThingConfiguration.class }) class MockitoAndTestBeanTests { @TestBean Gizmo gizmo; @TestBean(name = "blueWidget", methodName = "makeBlueWidget") Widget blueWidget; static Gizmo gizmo() { return new Gizmo("test"); } static Widget makeBlueWidget() { return new Widget("test"); } } section 3.4
Listing 3.14 Providing beans with @TestBean
@SpringBootTest(classes = { ThingConfiguration.class })
class MockitoAndTestBeanTests {
@TestBean #1
Gizmo gizmo;
@TestBean(name = "blueWidget", methodName = "makeBlueWidget") #2
Widget blueWidget;
static Gizmo gizmo() { #3
return new Gizmo("test");
}
static Widget makeBlueWidget() { #3
return new Widget("test");
}
// ... your test code ...
}
Inspect the complete @TestBean example, including field names, bean names, methodName, and static factory methods. section 3.4
@TestBean changes the test application configuration and can contribute to additional cached test applications. Reuse consistent customizations where possible, and prefer it for focused bean replacement or missing-bean scenarios rather than accumulating many context variants. section 3.5.2 section 3.6
