@SpringBootTest not creating inner beans while loading the context

五迷三道 提交于 2019-12-12 04:04:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!