SpyBean
Annotation that can be used to apply Mockito spies to a Spring ApplicationContext. Can be used as a class level annotation or on fields in either @Configuration
classes, or test classes that are @RunWith the SpringRunner.
Spies can be applied by type or by bean name. All beans in the context of a matching type (including subclasses) will be wrapped with the spy. If no existing bean is defined a new one will be added. Dependencies that are known to the application context but are not beans (such as those registered directly) will not be found and a spied bean will be added to the context alongside the existing dependency.
When @SpyBean
is used on a field, as well as being registered in the application context, the spy will also be injected into the field. Typical usage might be:
@RunWith(SpringRunner.class)
public class ExampleTests {
@SpyBean
private ExampleService service;
@Autowired
private UserOfService userOfService;
@Test
public void testUserOfService() {
String actual = this.userOfService.makeUse();
assertEquals("Was: Hello", actual);
verify(this.service).greet();
}
@Configuration
@Import(UserOfService.class) // A @Component injected with ExampleService
static class Config {
}
}
@RunWith(SpringRunner.class)
public class ExampleTests {
@SpyBean
@Qualifier("example")
private ExampleService service;
...
}
This annotation is @Repeatable
and may be specified multiple times when working with Java 8 or contained within a @SpyBeans annotation.
Author
Phillip Webb
Since
1.4.0