我正在尝试使用 application.properties 配置文件使用 JUnit 进行集成测试,以检查两个不同的平台。
我尝试使用基本配置文件 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 测试中是否有特殊的方法来指定 spring profile?实现我想要做的事情的最佳实践是什么?
最佳答案
首先:将 @ActiveProfiles
添加到您的测试类以定义 Activity 配置文件。
此外,您需要配置应该加载的配置文件。有两种选择:
- 在使用
@ContextConfiguration(classes = TheConfiguration.class, initializers = ConfigFileApplicationContextInitializer.class)
的简单集成测试中
- 在完整的 Spring Boot 测试中使用
@SpringBootTest
示例测试类:
@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
。
关于java - Spring-boot,JUnit 测试使用不同的配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52353127/