@TestBean
@TestBean
is used on a field in a test class to override a specific bean in the test’s
ApplicationContext
with an instance provided by a factory method.
The associated factory method name is derived from the annotated field’s name, or the
bean name if specified. The factory method must be static
, accept no arguments, and
have a return type compatible with the type of the bean to override. To make things more
explicit, or if you’d rather use a different name, the annotation allows for a specific
method name to be provided.
By default, the annotated field’s type is used to search for candidate beans to override.
If multiple candidates match, @Qualifier
can be provided to narrow the candidate to
override. Alternatively, a candidate whose bean name matches the name of the field will
match.
A bean will be created if a corresponding bean does not exist. However, if you would like
for the test to fail when a corresponding bean does not exist, you can set the
enforceOverride
attribute to true
– for example, @TestBean(enforceOverride = true)
.
To use a by-name override rather than a by-type override, specify the name
attribute
of the annotation.
Qualifiers, including the name of the field, are used to determine if a separate
|
The following example shows how to use the default behavior of the @TestBean
annotation:
-
Java
class OverrideBeanTests {
@TestBean (1)
private CustomService customService;
// test case body...
private static CustomService customService() { (2)
return new MyFakeCustomService();
}
}
1 | Mark a field for overriding the bean with type CustomService . |
2 | The result of this static method will be used as the instance and injected into the field. |
In the example above, we are overriding the bean with type CustomService
. If more than
one bean of that type exists, the bean named customService
is considered. Otherwise,
the test will fail, and you will need to provide a qualifier of some sort to identify
which of the CustomService
beans you want to override.
The following example uses a by-name lookup, rather than a by-type lookup:
-
Java
class OverrideBeanTests {
@TestBean(name = "service", methodName = "createCustomService") (1)
private CustomService customService;
// test case body...
private static CustomService createCustomService() { (2)
return new MyFakeCustomService();
}
}
1 | Mark a field for overriding the bean with name service , and specify that the
factory method is named createCustomService . |
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 Alternatively, a factory method in an external class can be referenced via its
fully-qualified method name following the syntax |
Only singleton beans can be overridden. Any attempt to override a non-singleton bean will result in an exception. When overriding a bean created by a |