Get Configuration Property class bean in SpringBoot Tests

Viewed 307

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??

2 Answers

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

}

Add @EnableConfigurationProperties(value = MyAppProperties.class) to your test class:

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

  @Autowired
  private RestTemplate restTemplate;

  @Autowired
  public MyAppProperties myAppProperties;

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