这是我在 Spring Boot 项目中使用的 Spring @Configuration
注释类:
@Configuration
@ImportResource({
"classpath:cat/gencat/ctti/canigo/arch/web/rs/config/canigo-web-rs.xml",
"classpath:cat/gencat/ctti/canigo/arch/core/i18n/config/canigo-core-i18n.xml"
})
public class WebServicesConfiguration {
如您所见,我正在导入第三方声明的资源。
尽管如此,我试图避免将它们导入到我的测试中。目前,我正在尝试创建测试来测试数据库通信。我不需要加载这些资源。
我怎样才能得到它?
这是我的相关代码片段:
@RunWith(SpringRunner.class)
@SpringBootTest()
public class ModelTest {
@Autowired
private MongoTemplate mongoTemplate;
因此,我想避免在 ModelTest
运行时加载 WebServicesConfiguration
配置类。
有什么想法吗?
最佳答案
您可以使用Spring Profiles来实现您的场景。
首先,将配置文件注释添加到您的配置中。请注意,您可以将多个配置文件添加到单个配置中(如下面的片段所示),并且如果任何指定的配置文件处于事件状态,则将应用该配置。
@Configuration
@ImportResource({
"classpath:cat/gencat/ctti/canigo/arch/web/rs/config/canigo-web-rs.xml",
"classpath:cat/gencat/ctti/canigo/arch/core/i18n/config/canigo-core-i18n.xml"
})
@Profile(value = {"dev", "prod"})
public class WebServicesConfiguration {
}
然后,在测试端定义您想要在测试中激活哪些配置文件。
@RunWith(SpringRunner.class)
@SpringBootTest()
@ActiveProfiles(profiles = {"test"})
public class ModelTest {
@Autowired
private MongoTemplate mongoTemplate;
}
关于 Spring 测试: Avoid to load configuration class on test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52474965/