liveBook · Manning

@TestBean

As explained in Testing Spring Boot Applications

@TestBean is a Spring testing annotation that replaces or supplies a bean in an application context with a test-specific bean.

@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

How Testing Spring Boot Applications covers it

How deep it goes
Explains factory lookup, naming overrides, external methods, and dependency avoidance, while deferring broader context-cache mechanics.
Examples
Uses Gizmo and Widget fields backed by static factories returning test-configured instances.
What it assumes
Assumes familiarity with Spring application contexts, @SpringBootTest, test beans, and static factory methods.
What you can do after
Build test-specific beans with static factories while avoiding Mockito APIs and unnecessary production dependencies.
How it connects
Connects @TestBean with @SpringBootTest, application contexts, @MockitoBean, Mockito, and Spring TestContext Framework caching.

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.