Spring启动:未在Test类中设置属性值

问题描述 投票:0回答:2

以下是我的项目结构

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

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

应用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
2个回答
0
投票

根据@ConfigurationProperties文件:

getter和setter通常是必需的,因为绑定是通过标准Java Beans属性描述符进行的。

private String sameUrl的setter是setSameUrl和NOT setsameUrl。

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


0
投票

不幸的是@TestPropertySource或@PropertySource不支持yml文件。

我不认为@TestPropertySource的文档在这个事实上是清楚的,但是以下的JIRA已经关闭。其中一条评论说......

@TestPropertySource中的locations属性已提供以下文档:

支持的文件格式

支持传统和基于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。

© www.soinside.com 2019 - 2024. All rights reserved.