@SpringBootTest在加载上下文时不创建内部bean

时间:2017-08-05 14:04:27

标签: spring spring-boot junit spring-test

我想了解为什么在尝试如下测试时不会创建内部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})

时,它会有效

2 个答案:

答案 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);
}
}