spring-boot Testing in Spring Boot Loading different yaml [or properties] file or override some properties


Example

When we use @SpringApplicationConfiguration it will use configuration from application.yml [properties] which in certain situation is not appropriate. So to override the properties we can use @TestPropertySource annotation.

@TestPropertySource(
        properties = {
                "spring.jpa.hibernate.ddl-auto=create-drop",
                "liquibase.enabled=false"
        }
)
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTest{

    // ...

}

We can use properties attribute of @TestPropertySource to override the specific properties we want. In above example we are overriding property spring.jpa.hibernate.ddl-auto to create-drop. And liquibase.enabled to false.

Loading different yml file

If you want to totally load different yml file for test you can use locations attribute on @TestPropertySource.

@TestPropertySource(locations="classpath:test.yml")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTest{

    // ...

}

Alternatively options

Option 1:

You can also load different yml file my placing a yml file on test > resource directory

Option 2:

Using @ActiveProfiles annotation

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@ActiveProfiles("somename")
public class MyIntTest{
}

You can see we are using @ActiveProfiles annotation and we are passing the somename as the value.

Create a file called application-somename.yml and and the test will load this file.