Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to autowire beans in test class when using @SpringBootTest

I have an integration test class annotated with @SpringBootTest which starts up the full application context and lets me execute my tests. However I am unable to @Autowired beans into the test class itself. Instead I get an error:

No qualifying bean of type 'my.package.MyHelper' available".

If I do not @Autowire my helper class, but keep the code directly inside the setUp function, the test works as expected.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class)
public class CacheControlTest {

    @Autowired
    private MyHelper myHelper;

    @Before
    public void setUp() {
        myHelper.doSomeStuff();
    }

    @Test
    public void test1() {
        // My test
    }
}

How can I make use of Spring autowiring inside the test class while also using @SpringBootTest?

Following @user7294900 advice below, creating a separate @Configuration file and adding this at the top of CacheControlTest works:

@ContextConfiguration(classes = { CacheControlTestConfiguration.class })

However is there any way of keeping the configuration inside the CacheControlTest class itself? I have tried adding inside my test class:

public class CacheControlTest {

    @TestConfiguration
    static class CacheControlTestConfiguration {
        @Bean
        public MyHelper myHelper() {
            return new MyHelper();
        }
    }

}

And

public class CacheControlTest {

    @Configuration
    static class CacheControlTestConfiguration {
        @Bean
        public MyHelper myHelper() {
            return new MyHelper();
        }
    }
}

But they do not seem to have any effect. I still get the same error. The same configuration block works when placed in an separate file as mentioned above though.

like image 480
Tarmo Avatar asked Oct 16 '22 09:10

Tarmo


1 Answers

Add ContextConfiguration for your Test Class:

@ContextConfiguration(classes = { CacheControlTestConfiguration.class })
like image 135
user7294900 Avatar answered Oct 20 '22 22:10

user7294900