Search code examples
javaspringspring-bootspring-testspring-boot-test

Get Configuration Property class bean in SpringBoot Tests


I have a class defined to auutomatically load properties from applicaton-*.properties in my sprintboot applicatoin:

@Component
@ConfigurationProperties("my-app")
@EnableConfigurationProperties
@Data
public class MyAppProperties {

  private String propertyX;
  private String propertyY;

..

}

Now here is my Test class:

@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
public class MessageProcessorApplicationTests {

  @Autowired
  private static RestTemplate restTemplate;

  @Autowired
  public static MyAppProperties myAppProperties;

  @Test
  public void testSomething(){
     doSomeSeetup(myAppProperties.getPropertyX()) //myAppProperties is null!! why?
}

In my test, the myAppProperties is always null. How do i get instance of this in my test??


Solution

  • Annotate MessageProcessorApplicationTests with @RunWith(SpringRunner.class) to auto load application.properties file

    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
    public class MessageProcessorApplicationTests {
    
    @Autowired
      private static RestTemplate restTemplate;
    
      @Autowired
      public static MyAppProperties myAppProperties;
    
      @Test
      public void testSomething(){
         doSomeSeetup(myAppProperties.getPropertyX());
    
    }