我有一个希望借助测试工具的@SpringBootTest
注解测试类:
package org.myproject.server;
// ...
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ServerITest {
private @Autowired TestHelperBean helper;
// ...
}
如果TestHelperBean
在相同的封装中测试类(或子包)所限定的本工作正常。
package org.myproject.server;
import org.springframework.stereotype.Component;
@Component
public class TestHelperBean {
// ...
}
如果我把它移动到兄弟包虽然,该组件没有找到:
org.springframework.beans.factory.NoSuchBeanDefinitionException:无型“org.myproject.testutils.TestHelperBean”提供的符合条件的bean:预计将有至少1 Bean上有资格作为自动装配候选人。依赖注解:{@ org.springframework.beans.factory.annotation.Autowired(所需=真)}
我想,默认组件扫描只查找测试类的包和子包 - 但有没有办法覆盖此默认?我试图@ComponentScan
注释添加到我的测试,但这似乎并没有产生任何影响:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ComponentScan("org.myproject")
public class ServerITest {
// ...
}
有没有办法使用从邻近的包豆春季启动测试的方法吗?
如果放在测试类的@ComponentScan
注释不起作用。
这可以替代来完成:
@Configuration
的@ComponentScan
注解类。@Import
注解。需要注意的是@Import
只允许个人类添加到背景。@ComponentScan
类(或@Configuration
,@Component
等)@Service
注解。在组件扫描您可以添加多个包需要被扫描
@ComponentScan({"org.myproject","org.myproject. server","org.myproject. sibilings"})
随着componentscan注释,你可以指定“*”覆盖基础包下的所有子包为好。
@ComponentScan({"org.myproject.*", "org.newproj.*"})
它涵盖在“org.myproject”和“org.newproj”的所有子包。
实施例的封装结构
org.myproject
org.myproject.abc
org.myproject.abcd
org.myproject.xyz.abc
org.newproj
org.newproj.abc
org.newproj.xyz
要么
与配置/ SpringBootApplication类注册豆
@Bean
private TestHelperBean helper() {
return new TestHelperBean();
}
关于使用ComponentScan
的其他的答案是正确的。然而,the Spring Boot documentation强烈建议“您的主应用程序类是一个根包以上的其他类”。从个人的经验,我可以说,这种做法偏离将导致更多的麻烦比它的价值。