Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 403
Simo Avatar asked Feb 03 '26 06:02

Simo


1 Answers

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

like image 180
NiVeR Avatar answered Feb 05 '26 19:02

NiVeR