【问题标题】:how to automatically use test properties file for tests and source properties file for app execution如何自动使用测试属性文件进行测试和源属性文件进行应用程序执行
【发布时间】:2020-06-19 05:02:15
【问题描述】:

我有一个带有源代码和测试层次结构的 Spring Boot 应用程序。 在这两个层次结构中,我都有带有属性的 application.yml 文件。

假设我在 src application.yml 中有以下内容:

settings1:
    setting1: value11
settings2
    setting1: value12

而在测试中的 application.yml 中,我有以下内容:

settings1:
    setting1:testValue11

我希望我的所有测试都知道测试 application.yml 中的覆盖值,如果测试 application.yml 中不存在某个值,则将从 src application.yml 中获取该值。

但我希望当我的应用程序运行时,它只知道来自 src application.yml 的设置。

我该如何解决?配置比在代码中连接值更可取。

【问题讨论】:

    标签: spring spring-boot properties configuration


    【解决方案1】:

    请参阅 Spring Boot 参考文档中的 2.7.3. Multi-profile YAML Documents 部分。

    单个 application.yml 文件的示例如下。

    settings1:
        setting1: 192.168.1.100
    settings2:
        setting1: 192.168.1.101
    ---
    spring:
        profiles: test
    settings1:
        setting1: 192.168.1.102
    

    还有一个测试用例如下

    @SpringBootTest
    @ActiveProfiles("test")
    class ApplicationTest {
    
        @Value("${settings1.setting1}")
        String setting1;
    
        @Value("${settings2.setting1}")
        String setting2;
    
        @Test
        void test() {
            System.out.println(setting1);
            System.out.println(setting2);
        }
    
    }
    

    将打印测试用例

    192.168.1.102

    192.168.1.101

    编辑

    对于单独/多个 yml 文件,

    除了application.yml,还有一个单独的application-<profile>.yml(这里是application-test.yml)来定义配置文件的特定属性。配置文件特定配置将优先于该配置文件处于活动状态。

    例如,定义application-test.yml

    settings1:
        setting1: 192.168.1.102
    

    【讨论】:

    • 好吧,你的方法是 1 个文件而不是 2 个。此外,我不想在每个测试类上写下它的活动配置文件是什么。我希望它在某些配置中全局设置。我怀疑解决方案涉及引导,但不确定如何。
    • 对于单独的文件,通读直到答案结束。对于全局测试配置文件,请尝试 SO question 中的answers。有多种方法可以引导相同的
    • 正如我所说,我想要一个用于测试和执行应用程序的差异配置。每次运行应用程序然后运行测试时,我都不会真正更改活动配置
    • application.yml 将是默认配置,应用程序运行时不需要单独的激活/配置文件。在使用 test-profile 进行测试时,application-test.yml 将与 application.yml 条目一起优先考虑。如果我正确理解您的担忧,那么每次运行应用程序时配置不会有任何更改,并且当使用 test 配置文件运行测试时,会考虑覆盖的属性。抱歉,如果这没有帮助。
    猜你喜欢
    • 2010-11-02
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    相关资源
    最近更新 更多