Spring-boot, JUnit tests using different profiles(Spring-boot,使用不同配置文件的JUnit测试)
问题描述
我正在尝试使用JUnit使用application.properties配置文件进行集成测试,以便检查两个不同的平台。
我尝试使用包含两个平台通用配置的基本配置文件application.properties
执行此操作,在此基础上,我为每个平台添加了具有特定平台配置的属性文件application-tensorflow.properties
application-caffe.properties
,但我发现它在JUnit中的工作方式与我在主应用程序中使用的方法不同。
我的测试配置类如下所示:
@Configuration
@PropertySource("classpath:application.properties")
@CompileStatic
@EnableConfigurationProperties
class TestConfig {...}
我使用的是@PropertySource("classpath:application.properties")
,所以它会识别我的基本配置,我在那里也写了spring.profiles.active=tensorflow
,希望它能识别TensorFlow应用程序配置文件,但是它不会像在主应用程序中那样从文件/src/test/resources/application-tensorflow.properties
或/src/main/resources/application-tensorflow.properties
中读取。
在JUnit测试中是否有指定弹簧配置文件的特殊方法?实现我正在尝试的目标的最佳实践是什么?
推荐答案
首先:将@ActiveProfiles
添加到您的测试类以定义活动配置文件。
- 在与
@ContextConfiguration(classes = TheConfiguration.class, initializers = ConfigFileApplicationContextInitializer.class)
的简单集成测试中
- 在使用
@SpringBootTest
的完全Spring Boot测试中
测试类示例:
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({ "test" })
public class DummyTest {
@Autowired
private Environment env;
@Test
public void readProps() {
String value = env.getProperty("prop1") + " " + env.getProperty("prop2");
assertEquals("Hello World", value);
}
}
现在评估文件src/test/resources/application.properties
和src/test/resources/application-test.properties
。
这篇关于Spring-boot,使用不同配置文件的JUnit测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Spring-boot,使用不同配置文件的JUnit测试


基础教程推荐
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01