繁体   English   中英

如何将application.properties加载到测试类中以获取spring.profiles.active值?

[英]How I can load application.properties into test class for getting the spring.profiles.active value?

我正在编写仅适用于特定配置文件的集成测试。 问题是我应该从application.properties文件中的spring.profiles.active值获取配置文件名称。 但是由于application.properties的实际价值,我总是得到null。

我为主要方法创建了方法,该方法明确将值放入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));
   }

但是该值仍然为null。 在测试类中,我使用以下注释:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyApplication.class)
@SpringBootTest(classes=MyApplication.class)

为了从主类加载上下文,我手动设置了必要的值。 也尝试使用@TestPropertySource("classpath:application.properties")但没有帮助。 而且我无法对值进行硬编码。 应该只能从application.properties获取

更新这是我的错误。 我已经尝试过从静态方法获取值:/也许有人知道我可以通过使用该值禁用类测试吗? @IfProfileValue仍返回null,因此不适合。

更新我已经意识到禁用是没有用的,更好的方法是使用@SpringBootTest(classes = AppropriateConfigClass.class)使用适当的配置

我将选择“ argskshitiz”作为解决方案,因为他是唯一尝试提供帮助的人。

你在那儿 @TestPropertySourcesrc/test/resources读取。 使用覆盖的值添加src/test/resources/application.properties ,您应该已完成。

@gargkshitiz的回答是完美的!

如果您只有属性spring.profiles.active要读取,则可以按照以下方式提及它(这将使我们免于维护属性文件)。

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
                value={"spring.profiles.active=yourActiveProfileName"})

您还可以指定多个属性,

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
                value={"spring.profiles.active=yourActiveProfileName",
                       "spring.some.other.property=propertyValue"})

如果不需要,可以删除webEnvironment = WebEnvironment.RANDOM_PORT

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM