FrVaBe FrVaBe - 1 year ago 298
Java Question

Override default Spring-Boot settings in Junit Test

I have a Spring-Boot application where the default properties are set in an
file in the classpath (src/main/resources/

I would like to override some default settings in my JUnit test with properties declared in a
file (src/test/resources/

I usualy have a dedicated Config Class for my Junit Tests, e.g.


import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

public class TestConfig {


I first thought that using
in the TestConfig class would do the trick, but these properties will not overwrite the settings (see Spring-Boot Reference Doc - 23. Externalized Configuration).

Then I tried to use
when invoking the test. That was successful - but I don't want to set this system property for each test execution. Thus I put it in the code

public class TestConfig {

static {
System.setProperty("spring.config.location", "");


which unfortunatly was again not successful.

There must be a simple solution on how to override
settings in JUnit tests with
that I must have overlooked.

Answer Source

You can use @TestPropertySource to override values in From its javadoc:

test property sources can be used to selectively override properties defined in system and application property sources

For example:

@SpringApplicationConfiguration(classes = ExampleApplication.class)
public class ExampleApplicationTests {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download