spring - 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
。
有任何想法吗?
解决方案
您可以使用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;
}
推荐阅读
- angularjs - Angular 应用程序,但量角器在某些情况下会找到 Angular,但在其他情况下不会
- angular - 以编程方式单击子组件表单中的按钮
- r - [[ ]] vs $:为什么后者在这个 Datacamp 代码上不起作用?
- tensorflow - Tensorflow 1.4 寻找 libcudnn.so.6 而不是 libcudnn.so.8
- git - 连接到 Github 以自动化克隆和拉取请求时的最佳实践?
- python - 使用 Python 将 json 解析为 Insert 语句
- php - Fix query to fetch all rows matching a query into associative array instead of just one
- java - 是否可以在应用第二次启动时使用 SharedPreferences 来更改 WebView 的默认 loadUrl?
- python - 为自定义“即将到来”过滤器扩展 Django-admin 的 DateFieldListFilter
- c# - 如何获取 XML 节点的值?