0

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})

Barath
  • 5,093
  • 1
  • 17
  • 42

2 Answers2

2

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).

Nikolai
  • 760
  • 4
  • 9
  • Example Implementation on the question of https://stackoverflow.com/questions/50592985/spring-boot-test-no-qualifying-bean-of-type-com-example-myservice-available – biniam Nov 02 '18 at 12:49
1

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);
}
}
Valeriy K.
  • 2,616
  • 1
  • 30
  • 53