Override default Spring-Boot application.properties settings in Junit Test
You can use @TestPropertySource
to override values in application.properties
. From its javadoc:
test property sources can be used to selectively override properties defined in system and application property sources
For example:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ExampleApplication.class)
@TestPropertySource(locations="classpath:test.properties")
public class ExampleApplicationTests {
}
You can also use meta-annotations to externalize the configuration. For example:
@RunWith(SpringJUnit4ClassRunner.class)
@DefaultTestAnnotations
public class ExampleApplicationTests {
...
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@SpringApplicationConfiguration(classes = ExampleApplication.class)
@TestPropertySource(locations="classpath:test.properties")
public @interface DefaultTestAnnotations { }
Spring Boot automatically loads src/test/resources/application.properties
, if following annotations are used
@RunWith(SpringRunner.class)
@SpringBootTest
So, rename test.properties
to application.properties
to utilize auto configuration.
If you only need to load the properties file (into the Environment) you can also use the following, as explained here
@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
[Update: Overriding certain properties for testing]
- Add
src/main/resources/application-test.properties
. - Annotate test class with
@ActiveProfiles("test")
.
This loads application.properties
and then application-test.properties
properties into application context for the test case, as per rules defined here.
Demo - https://github.com/mohnish82/so-spring-boot-testprops