Cannot load context properties in a Spring Boot test

HungryBird :

I try to write a test for a method which uses the attributes defined in the application.properties, but it seems that the Spring context cannot be loaded in the test.

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());
    }
}

The result of this test is nullnullnull, can anyone tell me how to solve this problem?

Karol Dowbecki :

@ConfigurationProperties requires both getters and setters for the fields representing a property. You have not declared them in your code so Spring Boot thinks there are no properties to inject.

Add the missing methods:

@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;
  }

} 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=161449&siteId=1