I have a @SpringBootTest
annotated test class which wants to make use of a test utility:
package org.myproject.server;
// ...
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ServerITest {
private @Autowired TestHelperBean helper;
// ...
}
This works fine if the TestHelperBean
is defined in the same package as the test class (or in a sub-package).
package org.myproject.server;
import org.springframework.stereotype.Component;
@Component
public class TestHelperBean {
// ...
}
If I move it to a sibling package though, the component is not found:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.myproject.testutils.TestHelperBean' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
I guess that component scanning by default only looks in the test class' package and sub-packages – but is there a way to override this default? I tried to add the @ComponentScan
annotation to my test, but this didn't seem to have any effect:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ComponentScan("org.myproject")
public class ServerITest {
// ...
}
Is there a way to use beans from sibling packages in Spring Boot tests?
The @ComponentScan
annotation doesn't work if placed on the test class.
This can be done instead:
@Configuration
and the @ComponentScan
annotation.@Import
annotation on the test class. Note that @Import
only allows to add individual classes to the context.@ComponentScan
annotation on any @Configuration
class (or @Component
, @Service
, etc.) that is already included in the context.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