问题
I would like to learn why inner beans are not created while trying to test like below :
RunWith(SpringRunner.class)
@SpringBootTest(classes=MyTest.class)
public class MyTest {
@SpyBean A a;
@Test
public void myTest() {
assertTrue(a.some());
}
@Component
class A {
private B b;
A(B dependency) {
this.b = dependency;
}
boolean some() {
return b.value();
}
}
@Configuration
class B {
boolean value() { return true; }
}
}
Error: No qualifying bean of type 'com.example.MyTest$B' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations:
Despite annotating the inner class with @Configuration it is not creating the bean while testing the method.
please note it works when I add like below @SpringBootTest(classes=MyTest.class,MyTest.B.class,MyTest.A.class})
回答1:
Add @ContextConfiguration(classes = MyTest.B.class)
to the MyTest class.
But
putting configuration into a test class isn't the best idea. It's better to create separate configuration class MyTestConfig
that create all need beans for test and use it in the test class by @ContextConfiguration(classes = MyTestConfig.class)
.
回答2:
Use @MockBean. And add behavior in @Test:
@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
public abstract class IntegrationTest {
@MockBean
A a;
@Test
public void mySuperTest(){
Mockito.when(a.getById(Mockito.any())).thenReturn(someInstance);
Assert.assertEquals(a.getById("id"), someInstance);
}
}
来源:https://stackoverflow.com/questions/45522778/springboottest-not-creating-inner-beans-while-loading-the-context