编程语言
首页 > 编程语言> > java – Spring Boot:自定义属性配置和测试

java – Spring Boot:自定义属性配置和测试

作者:互联网

我正在使用Spring Boot 2.0和默认的application.yml属性文件.我想将它拆分为单独的属性文件,因为它变得很大.
此外,我想编写测试来检查属性的正确性:将出现在生产应用程序上下文中的值(而不是测试中的值).

这是我的属性文件:src / main / resources / config / custom.yml

my-property:
  value: 'test'

物业类:

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Data
@Configuration
@ConfigurationProperties(prefix = "my-property")
@PropertySource("classpath:config/custom.yml")
public class MyProperty {

  private String value;
}

测试:

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyProperty.class)
@EnableConfigurationProperties
public class MyPropertyTest {

  @Autowired
  private MyProperty property;

  @Test
  public void test() {
    assertEquals("test", property.getValue());
  }

}

但测试失败并出现错误:

java.lang.AssertionError: 
Expected :test
Actual   :null

另外,通过在ApplicationRunner中打印应用程序来运行应用程序时,我看到属性值为null.
当我将application.yml用于所有属性时,它具有相同的配置.

如何为属性和测试正确配置以使其工作?
链接到Github repo

解决方法:

很好,我找到了在我的应用程序中使用自定义yaml属性的正确方法.

问题是Spring不支持yaml文件为@PropertySource(link to issue).以下是如何处理spring documentation中描述的解决方法.
因此,为了能够从您需要的yaml文件加载属性:
*实现EnvironmentPostProcessor
*在spring.factories中注册

请访问此github repo以获取完整示例.

另外,非常感谢你的支持,伙计们!

标签:spring-boot-test,java,spring,spring-boot
来源: https://codeday.me/bug/20190910/1798753.html