0

I am a newbie with SpringBoot and I am trying to develop a first application.

My application has a configuration that is provided in an application.yaml. Currently, it successfully reads its configuration at startup.

However, if I embed my application in a Springboot/JUnit test, the application.yaml is not correctly exploited.

My impression is that, using Springboot/JUnit, application.yaml is read as if it was an application.properties: it only accepts parameters that are provided on a single line (e.g. thread-pool: 10) but not on a multi-line

wordpress:
  themes:
    default-folder: /wp-content/themes/mkyong

I reproduced the same issue from a project I found in github: https://github.com/mkyong/spring-boot.git, in the directory yaml-simple

the application successfully reads its configuration:

@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    private WordpressProperties wpProperties;

    @Autowired
    private GlobalProperties globalProperties;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) {
        System.out.println(globalProperties);
        System.out.println(wpProperties);
    }
}

But if I create the following JUnit test in the directory src/test/java/com/mkyong

@RunWith(SpringRunner.class)
@TestPropertySource(locations="classpath:application.yml")
public class MyTest {

    @Autowired
    private WordpressProperties wpProperties;

    @Autowired
    private GlobalProperties globalProperties;


    @Test
    public void myTest() {
        Assert.assertTrue(globalProperties.getThreadPool() == 10); /// OK
        Assert.assertEquals("/wp-content/themes/mkyong", wpProperties.getThemes().getDefaultFolder()); // KO
    }

    @SpringBootApplication
    static class TestConfiguration {
    }

}

while running it, the configuration is only partially read!!!

(please note that my problem does not appear using application.properties but I prefer yaml against properties)

Philippe MESMEUR
  • 737
  • 8
  • 22

1 Answers1

1

Thanks the answer of user7294900, I found that adding the annotation @ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class) to my test class solved the problem:

@RunWith(SpringRunner.class)
@TestPropertySource(locations="classpath:application.yml")
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
public class MyTest {

    @Autowired
    private WordpressProperties wpProperties;

    @Autowired
    private GlobalProperties globalProperties;


    @Test
    public void myTest() {
        Assert.assertTrue(globalProperties.getThreadPool() == 10);
        Assert.assertEquals("/wp-content/themes/mkyong", wpProperties.getThemes().getDefaultFolder());
    }

    @SpringBootApplication
    static class TestConfiguration {
    }

}
Philippe MESMEUR
  • 737
  • 8
  • 22