@Target(value=FIELD) @Retention(value=RUNTIME) @Repeatable(value=MockInBeans.class) public @interface MockInBean
Annotation used to inject a mockito Mock in a Spring Bean for the duration of a test.
This is a convenient alternative to @MockBean that provides surgical mock injection without dirtying or polluting the Spring context:
Mocks 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 Object returnSomethingFromThirdPartyApi() {
return thirdPartyApi.returnSomething();
}
}
You can create a test for your service with a mocked ThirdPartyApi like:
@SpringBootTest
public class MyServiceTest {
@MockInBean(MyService.class)
private ThirdPartyApi thirdPartyApi;
@Autowired
private MyService myService;
@Test
public void test() {
final Object expected = new Object();
Mockito.when(thirdPartyApi.returnSomething()).thenReturn(expected);
final Object actual = myService.returnSomethingFromThirdPartyApi();
Assert.assertEquals(expected, actual);
}
}
thirdPartyApi will be a Mock 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 mock has multiple instances registered in the context, you can specify the name of the bean:
@MockInBean(value = MyService.class, name = "nameOfMyService") private ThirdPartyApi thirdPartyApi;
You can also inject your mock in multiple beans by repeating the annotation:
@MockInBean(MyFirstService.class), @MockInBean(MySecondService.class) private ThirdPartyApi thirdPartyApi;
SpyInBeanpublic abstract Class<?> value
class of the Spring Bean in which you want your Mock to be injected for the duration of the test.public abstract String name
name of the Spring Bean in which you want your Mock to be injected for the duration of the test.Copyright © 2021. All rights reserved.