@Target(value=FIELD) @Retention(value=RUNTIME) @Repeatable(value=SpyInBeans.class) public @interface SpyInBean
Annotation used to inject a Spy of a Spring Bean in another Spring Bean for the duration of a test.
This is a convenient alternative to @SpyBean that provides surgical spy injection without dirtying or polluting the Spring context:
Spys are injected for every test method and the original Spring Beans(s) are re-injected after the test class is done.
Example:
Assuming you have the following service:
@Service
public class MyService {
@Autowired
private ThirdPartyApi thirdPartyApi;
public void doSomethingWithThirdPartyApi() {
thirdPartyApi.doSomething(new Object());
}
}
You can create a test for your service with a spied ThirdPartyApi like:
@SpringBootTest
public class MyServiceTest {
@SpyInBean(MyService.class)
private ThirdPartyApi thirdPartyApi;
@Autowired
private MyService myService;
@Test
public void test() {
myService.doSomethingWithThirdPartyApi();
Mockito.verify(thirdPartyApi).doSomething(Mockito.any(Object.class));
}
}
thirdPartyApi will be a Spy of the actual ThirdPartyApi Spring Bean that is recreated for every test method in MyServiceTest and MyService.ThirdPartyApi Spring bean will be re-injected in MyService after all the tests of MyServiceTest.
In case the bean in which you are trying to inject a spy has multiple instances registered in the context, you can specify the name of the bean:
@SpyInBean(value = MyService.class, name = "nameOfMyService") private ThirdPartyApi thirdPartyApi;
You can also inject your spy in multiple beans by repeating the annotation:
@SpyInBean(MyFirstService.class), @SpyInBean(MySecondService.class) private ThirdPartyApi thirdPartyApi;
MockInBeanpublic abstract Class<?> value
class of the Spring Bean in which you want your Spy to be injected for the duration of the test.public abstract String name
name of the Spring Bean in which you want your Spy to be injected for the duration of the test.Copyright © 2021. All rights reserved.