首页 > 解决方案 > Spring测试:避免在测试时加载配置类

问题描述

这是@Configuration我在 Spring Boot 项目中使用的 Spring 注释类:

@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;

所以,我想避免在运行WebServicesConfiguration时加载配置类ModelTest

有任何想法吗?

标签: springspring-bootspring-dataspring-data-mongodbspring-test

解决方案


您可以使用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;

}

推荐阅读