spring-mvcspring-boot

Load different application.yml in SpringBoot Test


I'm using a Spring Boot app which runs my src/main/resources/config/application.yml file.

When I run my test case by :

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
public class MyIntTest{
}

The test codes still run my application.yml file to load properties. I wonder if it is possible to run another *.yml file when running the test case.


Solution

  • I have tested @IlyaSerbis answer and it is working for me. I am using Spring Boot 2.3.

    I have tested these scenarios and it worked.

    Scenario1 - First I have created an application.yml file for jUnit purpose and put it under the src/test/resources/config directory (the same directory as the main application.yml file) where it completely replaces the original yaml file (not overwrite). That means it will not use any of the properties mentioned in application.yml of the src/main/resources/config directory (main directory).

    Note: In Scenario1, the path of application.yml in main and test need to be exactly same. If src/main/resources/config/application.yml then src/test/resources/config/application.yml. If src/main/resources/application.yml then src/test/resources/application.yml

    Scenario2 - Then I created the application-test.yml file instead of the application.yml file under the src/test/resources/config directory and using the @ActiveProfiles("test") annotation, I could see jUnit taking property values from the application-test.yml file (overwriting application.yml for common properties) and then taking values from application.yml as well that are not defined in application-test.yml.