无法在Spring Boot测试中加载上下文属性

时间:2019-01-14 22:24:18

标签: java spring unit-testing spring-boot junit

我尝试为使用application.properties中定义的属性的方法编写测试,但是似乎无法在测试中加载Spring上下文。

MyProperties.java

@Configuration
@PropertySource("classpath:application.properties")
@ConfigurationProperties(prefix = "test")
public class MyProperties {

    private String name;
    private String gender;
    private String age;

    public String getInformation(){
        return name + gender + age;
    }
} 

application.properties

test.name=JASON
test.gender=MALE
test.age=23

Test.java

@RunWith(SpringRunner.class)
@SpringBootTest
public class Test {

    @Autowired
    private MyProperties myProperties;

    @Test
    public void getInformation(){
        assertEquals("JASONMALE23", myProperties.getInformation());
    }
}

此测试的结果为 nullnullnull ,有人可以告诉我如何解决此问题吗?

1 个答案:

答案 0 :(得分:1)

@ConfigurationProperties要求代表属性的字段都使用getter和setter。您尚未在代码中声明它们,因此Spring Boot认为没有要注入的属性。

添加缺少的方法:

@Configuration
@PropertySource("classpath:application.properties")
@ConfigurationProperties(prefix = "test")
public class MyProperties {

  private String name;
  private String gender;
  private String age;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getGender() {
    return gender;
  }

  public void setGender(String gender) {
    this.gender = gender;
  }

  public String getAge() {
    return age;
  }

  public void setAge(String age) {
    this.age = age;
  }

  public String getInformation(){
    return name + gender + age;
  }

}