Spring boot test - No qualifying bean of type 'com.example.MyService' available

南笙酒味 提交于 2019-12-24 16:23:22

问题


There are a number of similar questions on stackoverflow, but I found none to be my case.

In my integration test with Spring boot 2.0.2.RELEASE, I created a separate @Configuration class for the test where I did define the bean com.example.MyService. This bean happens to be used by some other bean in com.example.OtherBean.

Here is the code:

Test class:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyIntegrationTestConfig.class},
        webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public class MyService1Test extends MyAbstractServiceIntegrationTest {
@Test
    public void someTest() {}
}

A common abstract for setup and teardown:

public class MyAbstractServiceIntegrationTest{
    @Before
    public void setUp(){}

    @After
    public void tearDown()
}

MyIntegrationTestConfig in src/test, to be used instead of the configs in the src/main:

@Configuration
@ComponentScan({"com.example"})
public class MyIntegrationTestConfig {
   @Bean
   public MyService myService() {
      return null;
   }
}

MyService bean can be null for testing purposes.

When I run the test, I keep getting the following error:

No qualifying bean of type 'com.example.MyService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

I even tried adding this inner class to MyServic1Test. Still didn't help:

@TestConfiguration
static class MyServic1TestContextConfiguration {

    @Bean(name = "MyService")
    public MyService myService() {
        return null;
    }
}

Any idea what I did wrong here? Or did I miss something?

My suspicion is that Spring tries to create/autowire beans in the src/main folder first before it even creates the MyService bean defined in src/test folder. Could that be the case? Or is there a different context (like test context) where bean MyService lives in, while the other beans live in an other context and could not locate MyService.

A side question: for integration test, it is OK to use webEnvironment = SpringBootTest.WebEnvironment.MOCK, correct?


回答1:


The problem is how you are initializing the bean. The value null is the one that causes the issue. It is as if you weren't infact declaring any instance of that object. To make it work declare a valid instance of the service new MyService().



来源:https://stackoverflow.com/questions/50592985/spring-boot-test-no-qualifying-bean-of-type-com-example-myservice-available

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