【问题标题】:How to test the binding of configuration properties in Spring Boot?如何在 Spring Boot 中测试配置属性的绑定?
【发布时间】:2021-12-30 15:45:28
【问题描述】:

我有一个带有以下(简化)配置类的 Spring Boot 应用程序

@ConfigurationProperties(prefix = "prefix")
@Configuration
public class ConfigProperties {
    @NotNull
    public Duration snapshotOffset;

}

我的代码正在运行,但我想知道如何使用不同的属性文件作为输入为绑定过程编写单元测试?

【问题讨论】:

    标签: java spring-boot unit-testing


    【解决方案1】:

    您可以使用TestPropertySource 注释的locationsvalue 属性来配置测试属性文件:

    //Typically, @TestPropertySource will be used in conjunction with @ContextConfiguration.
    @ContextConfiguration
    @TestPropertySource("/test.properties") 
    public class Test {
        // class body...
    }
    

    【讨论】:

    • 我一直在寻找一种解决方案,例如带有 try-catch-statement 的真实单元测试。
    • @Oliver 我不太明白,你能给我一个场景例子吗?
    猜你喜欢
    • 2020-06-14
    • 2018-11-14
    • 1970-01-01
    • 2017-01-08
    • 2019-04-15
    • 2021-05-22
    • 2019-04-26
    • 2018-03-08
    • 1970-01-01
    相关资源
    最近更新 更多