Using @MockitoSpyBean
in tests with parent-child contexts defined with @ContextHierarchy
fails with an IllegalStateException
:
java.lang.IllegalStateException: Unable to select a bean to wrap: there are no beans of type ...
at org.springframework.test.context.bean.override.BeanOverrideBeanFactoryPostProcessor.wrapBean(BeanOverrideBeanFactoryPostProcessor.java:273)
at org.springframework.test.context.bean.override.BeanOverrideBeanFactoryPostProcessor.registerBeanOverride(BeanOverrideBeanFactoryPostProcessor.java:116)
at org.springframework.test.context.bean.override.BeanOverrideBeanFactoryPostProcessor.postProcessBeanFactory(BeanOverrideBeanFactoryPostProcessor.java:100)
It seems that the BeanOverrideBeanFactoryPostProcessor
tries to wrap the target bean for each context in the hierarchy - failing for the context in which the target bean does not exist.
Code to reproduce this issue:
@ContextHierarchy({
@ContextConfiguration(classes = Config1.class),
@ContextConfiguration(classes = Config2.class)
})
@ExtendWith(SpringExtension.class)
class TestMockitoSpyBeanJUnit5 {
// @SpyBean // works
@MockitoSpyBean
private MyService myService;
@Test
void test() {
System.out.print(myService.getValue());
}
@Configuration
public static class Config1 {
@Bean
public MyService myService() {
return new MyService();
}
}
@Configuration
public static class Config2 {
}
public static class MyService {
public String getValue() {
return "New";
}
}
}
The exception occurs regardless of the order of Config1.class
and Config2.class
.