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?