2

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?

2
  • where have you put your application.properties? Make a separate application.proprties for test configs and put it under src/test/resources and spring boot will auto-load them Commented Jan 14, 2019 at 22:54
  • sorry, I can't test it but maybe classpath:/application.properties?=)) Commented Jan 14, 2019 at 22:55

1 Answer 1

1

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

} 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Karol, your solution is very helpful for me. Regarding the variable marked with @Value(${test}), it can inject the properties without the get and set method, why are they different?
@Value is something completely different, it's used to evaluate SpEL expressions. @ConfigurationProperties is just a convenient binding for properties into Java class. Two different parts of the framework with different rules.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.