Spring启动测试 - 找不到测试属性

Mar*_*tra 14 spring unit-testing spring-boot

我有一个春季启动项目,它很棒.我现在想为我的应用程序编写测试,我遇到了一些配置问题.

Spring boot为我创建了一个名为ApplicationTests的测试类.这很简单,看起来像这样:

@RunWith(SpringRunner.class)
@SpringBootTest
public class DuurzaamApplicationTests {
    @Test
    public void contextLoads() {
    }    
}
Run Code Online (Sandbox Code Playgroud)

现在,当我开始测试时,我收到此错误:

java.lang.IllegalArgumentException: Could not resolve placeholder 'company.upload' in value "${company.upload}"
Run Code Online (Sandbox Code Playgroud)

我在src/test/resources目录中有一个properties.yml文件,由于某种原因它没有加载.我从互联网上的例子中尝试了所有不同类型的注释,但它们都没有工作.

如何告诉spring boot测试使用application.yml文件加载属性?

Bar*_*ath 12

我们可以使用@TestPropertySource@PropertySource加载属性文件

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource("classpath:properties.yml")
@ActiveProfiles("test")
public class DuurzaamApplicationTests {
    @Test
    public void contextLoads() {
    }    
}
Run Code Online (Sandbox Code Playgroud)

文档:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/TestPropertySource.html

  • 使用@ActiveProfiles("test")并尝试 (5认同)
  • 不行.我仍然得到"无法解决占位符'company.upload'的值"$ {company.upload}".我的application.yml位于src/test/resources目录中. (4认同)

Wes*_*Gun 5

令我惊讶的是,当您在Spring Boot Test中加载属性文件时,.yml不被支持。在文档中已对此进行了说明,尽管是隐式的。

从上面的链接:

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/TestPropertySource.html

支持的文件格式

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

.yml 没有提到。

并且,在将my更改.yml.properties并重写xx.xx.xx=value格式的值之后,可以正确读取键值对。

这么奇怪。

编辑:

现在,我找到了解决该问题的票证;似乎是Spring中一个众所周知的错误。

https://github.com/spring-projects/spring-framework/issues/18486