@TestBean

@TestBean is used on a test class field to override a specific bean in the test’s ApplicationContext with an instance provided by a conventionally named static factory method.

By default, the bean name and the associated factory method name are derived from the annotated field’s name, but the annotation allows for specific values to be provided.

The @TestBean annotation uses the REPLACE_DEFINITION strategy for test bean overriding.

The following example shows how to fully configure the @TestBean annotation, with explicit values equivalent to the defaults:

  • Java

class OverrideBeanTests {
	@TestBean(name = "service", methodName = "serviceTestOverride")  (1)
	private CustomService service;

	// test case body...

	private static CustomService serviceTestOverride() { (2)
		return new MyFakeCustomService();
	}
}
1 Mark a field for bean overriding in this test class.
2 The result of this static method will be used as the instance and injected into the field.
Spring searches for the factory method to invoke in the test class, in the test class hierarchy, and in the enclosing class hierarchy for a @Nested test class.