【问题标题】:How I can load application.properties into test class for getting the spring.profiles.active value?如何将 application.properties 加载到测试类中以获取 spring.profiles.active 值?
【发布时间】: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


    【解决方案1】:

    你已经成功了一半。 @TestPropertySource 读取自 src/test/resources。添加带有覆盖值的src/test/resources/application.properties,您应该完成。

    【讨论】:

      【解决方案2】:

      @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

      【讨论】:

        猜你喜欢
        • 2021-05-08
        • 1970-01-01
        • 2021-06-26
        • 2021-11-14
        • 1970-01-01
        • 2021-03-15
        • 2020-03-31
        • 1970-01-01
        • 2017-11-29
        相关资源
        最近更新 更多