【问题标题】:Spring boot : Properties values not getting set in Test classSpring boot:未在测试类中设置属性值
【发布时间】:2023-03-31 14:47:01
【问题描述】:

下面是我的项目结构

SomeProject
    -src/main/java
    -src/main/resources
    -src/test/java
    -src/test/resources
        application-test.yml

以下是我的属性文件的内容

application-test.yml

pre:
    someUrl: http://someurl

下面是配置类的内容

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "pre")
public class SomeConfiguration {

    private String someUrl;

    public String getsomeUrl() {
        return someUrl;
    }

    public void setsomeUrl(String someUrl) {
        this.someUrl = someUrl;
    }
}

下面是我的测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SomeConfiguration.class)
@TestPropertySource(locations = {"classpath:application-test.yml"})
public class SomeServiceTest {

    SomeObject someObject;

    @Autowired
    private SomeConfiguration someConfiguration; 

    @Test
    public void somMethodTest() {
        someObject = new SomeObject ();
        someObject.setsomeUrl(someConfiguration.getsomeUrl());

    }
}

问题是当我尝试在 someObject 中设置 someURL 时,我得到了 null。我在 stackoverflow 上看到了类似的问题并接受了答案,但我仍然得到空值。

【问题讨论】:

    标签: java spring spring-boot junit


    【解决方案1】:

    根据@ConfigurationProperties 文档:

    Getter 和 setter 通常是强制性的,因为绑定是通过 标准 Java Bean 属性描述符。

    private String sameUrl 的设置器是 setSameUrl 而不是 setsameUrl

    所以 spring 可能会从属性文件中读取它,但它不能通过 setter 注入它。

    【讨论】:

      【解决方案2】:

      很遗憾,@TestPropertySource 或 @PropertySource 不支持 yml 文件。

      我认为@TestPropertySource 的文档并不清楚这一事实,但以下JIRA 已关闭。其中一位 cmets 说...

      @TestPropertySource 中的位置属性已经提供了以下文档:

      支持的文件格式

      支持传统和基于 XML 的属性文件格式,例如“classpath:/com/example/test.properties”或“file:/path/to/file.xml”。

      spring docs 中的以下内容为@PropertySource 拼写出来:

      24.7.4 YAML 缺点

      无法使用 @PropertySource 注解加载 YAML 文件。 因此,如果您需要以这种方式加载值,则需要使用 属性文件。

      如果你create a suitable factory,你可以让@PropertySource 加载yaml,不确定你是否可以用@TestPropertySource 来做。

      【讨论】:

        猜你喜欢
        • 2017-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-13
        • 2020-11-03
        • 1970-01-01
        • 2019-04-15
        • 2021-03-06
        相关资源
        最近更新 更多