And*_*r1i 3 java junit spring-boot
我正在编写集成测试,它应该只适用于特定的配置文件。问题是我应该从 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));
}
Run Code Online (Sandbox Code Playgroud)
但该值仍然为空。在测试类中,我使用以下注释:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyApplication.class)
@SpringBootTest(classes=MyApplication.class)
Run Code Online (Sandbox Code Playgroud)
对于从主类加载上下文,我手动设置了必要的值。也尝试使用@TestPropertySource("classpath:application.properties")
但没有任何帮助。而且我无法对该值进行硬编码。它应该只能从 application.properties 获取
更新 这是我的错误。我已经从静态方法中尝试过 getValue :/ 也许有人知道如何通过使用这个值来禁用类测试?@IfProfileValue 仍然返回 null,因此不适合。
更新 我意识到禁用是无用的,最好使用@SpringBootTest(classes=AppropriateConfigClass.class) 使用适当的配置
我会选择gargkshitiz作为已解决的答案,因为他是唯一一个试图提供帮助的人。
你已经成功了一半。@TestPropertySource从src/test/resources. 添加src/test/resources/application.properties覆盖的值,您应该完成。
| 归档时间: |
|
| 查看次数: |
4977 次 |
| 最近记录: |