我想了解为什么在尝试如下测试时不会创建内部bean:
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; }
}
}
错误:No qualifying bean of type 'com.example.MyTest$B' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations:
尽管使用@Configuration注释了内部类,但在测试方法时却没有创建bean。
请注意,当我添加如下@SpringBootTest(classes=MyTest.class,MyTest.B.class,MyTest.A.class})
答案 0 :(得分:2)
将@ContextConfiguration(classes = MyTest.B.class)
添加到MyTest类
但
将配置放入测试类并不是最好的主意。最好创建单独的配置类MyTestConfig
,为测试创建所有需要的bean,并在@ContextConfiguration(classes = MyTestConfig.class)
的测试类中使用它。
答案 1 :(得分:0)
使用@MockBean。并在@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);
}
}