【发布时间】:2018-09-04 05:54:48
【问题描述】:
我正在编写仅适用于特定配置文件的集成测试。问题是我应该从 application.properties 文件中的 spring.profiles.active 值获取配置文件名称。但由于 application.properties 的实际价值,我总是得到 null。
我为 main 方法创建了明确地将值放入 System.properties:
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Autowired
public MyApplication(Environment environment) {
String property = "spring.profiles.active";
System.getProperties().setProperty(property, environment.getProperty(property));
}
但该值仍然为空。 在测试类中,我使用以下注释:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyApplication.class)
@SpringBootTest(classes=MyApplication.class)
用于从我手动设置必要值的主类加载上下文。
还尝试使用@TestPropertySource("classpath:application.properties")
但没有任何帮助。而且我无法对值进行硬编码。它应该只能从 application.properties 获取
更新 这是我的错误。我已经尝试从静态方法获取值:/ 也许有人知道我如何通过使用这个值来禁用类测试? @IfProfileValue 仍然返回 null,因此不适合。
更新 我已经意识到禁用是没用的,最好使用@SpringBootTest(classes=AppropriateConfigClass.class) 使用适当的配置
我会选择 gargkshitiz 作为已解决的答案,因为他是唯一一个试图提供帮助的人。
【问题讨论】:
标签: java spring-boot junit