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.
Add ContextConfiguration for your Test Class:
@ContextConfiguration(classes = { CacheControlTestConfiguration.class })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With