297

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

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

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

package foo.bar.test;

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

@Configuration
@Import(CoreConfig.class)
@EnableAutoConfiguration
public class TestConfig {

}

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

Then I tried to use -Dspring.config.location=classpath:test.properties 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

@Configuration
@Import(CoreConfig.class)
@EnableAutoConfiguration
public class TestConfig {

  static {
    System.setProperty("spring.config.location", "classpath:test.properties");
  }

}

which unfortunatly was again not successful.

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

3

15 Answers 15

376

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 {

}
11
  • 6
    That's it. Thanks. Unfortuantly it does not work when used on the ExampleApplication.class so I have to set it on each test class. Is that right?
    – FrVaBe
    Commented Apr 16, 2015 at 11:53
  • 100
    Also note that @TestPropertySource can accept a properties argument to overwrite some property inline, such as @TestPropertySource(properties = "myConf.myProp=valueInTest"), it's useful in case that you don't want a totally brand new property file.
    – dyng
    Commented Feb 3, 2016 at 13:19
  • 3
    You can specify multiple files in an array, and also files on the file system (but remember they might not work on the CI server): @TestPropertySource(locations={"file:C:/dev/...","classpath:test.properties"})
    – Adam
    Commented Feb 3, 2017 at 13:21
  • 18
    Note, that @SpringApplicationConfiguration is already deprecated, and you should use @SpringBootTest Commented Nov 23, 2017 at 9:04
  • 3
    @Stefan It can be used if you make the test profile active. Commented Sep 5, 2018 at 8:43
118

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]

  1. Add src/main/resources/application-test.properties.
  2. 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

14
  • 4
    Not sure if it is a good idea to have two application.properties files on the classpath (one in src/main/resources and one in src/test/resources). Who guarantees that both will be taken and which one will be taken first?
    – FrVaBe
    Commented Jul 13, 2017 at 10:16
  • 7
    @FrVaBe Spring is going to guarantee it! Main profile properties are always loaded. Then during the test phase, test properties are loaded, adding/overriding new/existing properties. If you don't like keeping two files with same name, then you can add application-test.properties in src/main/resources and specify test as the active profile in the test case.
    – Mohnish
    Commented Jul 15, 2017 at 20:20
  • 18
    Spring does not give a guarantee. The build tool will use the test resources in favour of the main resources during tests. But in case of a test application.properties the main application.properties will be ignored. That is not what I want because the main one contains several useful default values and I only need to override some of them during the test (and I do not want to duplicate the whole file in the test section). See here.
    – FrVaBe
    Commented Jul 18, 2017 at 8:34
  • 13
    You're correct, only properties defined in src/test/resources/application.properties are loaded during the test phase, src/main/resources/application.properties is ignored.
    – Mohnish
    Commented Jul 18, 2017 at 16:13
  • 15
    If you do not use profiles so far you do not need a dedicated "test" profile. Just name your test properties application-default.properties and they will be considered because you are automatically running the "default" profile (if not declared any other).
    – FrVaBe
    Commented Jul 18, 2017 at 20:48
70

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 { }
0
68

Another approach suitable for overriding a few properties in your test, if you are using @SpringBootTest annotation:

@SpringBootTest(properties = {"propA=valueA", "propB=valueB"})
2
  • 3
    does SpringBootTest load the application.properties file? Commented Oct 7, 2019 at 21:02
  • 1
    @TuGordoBello yes
    – Sa'ad
    Commented Apr 9, 2021 at 18:17
27

If you are like me and you have the same application.properties in src/main/resources and src/test/resources, and you are wondering why the application.properties in your test folder is not overriding the application.properties in your main resources, read on...

Simple explanation:

If you have application.properties under src/main/resources and the same application.properties under src/test/resources, which application.properties gets picked up, depends on how you are running your tests. The folder structure src/main/resources and src/test/resources, is a Maven architectural convention, so if you run your test like mvnw test or even gradlew test, the application.properties in src/test/resources will get picked up, as test classpath will precede main classpath. But, if you run your test like Run as JUnit Test in Eclipse/STS, the application.properties in src/main/resources will get picked up, as main classpath precedes test classpath.

You can check it out by opening the menu bar Run > Run Configurations > JUnit > *your_run_configuration* > Click on "Show Command Line".

You will see something like this:

XXXbin\javaw.exe -ea -Dfile.encoding=UTF-8 -classpath
XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\main;
XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\test;

Do you see that classpath xxx\main comes first, and then xxx\test? Right, it's all about classpath :-)

Side-note: Be mindful that properties overridden in the Launch Configuration(In Spring Tool Suite IDE, for example) takes priority over application.properties.

Change the order:

Now, everything is configurable in Spring. You can change the build classpath, so that xxx\test comes first, and then xxx\main.

Simply go to Project > Properties > Java Build Path > Order and Export, change the build class path order by putting any of the test folder first such as:

enter image description here

And that's it!

Better solution

A better solution though, when testing, would be to activate the src/test/resources/application-{profile}.properties (where profile can be test), such as the following in src/main/resources/application.properties:

spring.profiles.active=test

This is neater, and gives you complete control on what profile to activate when doing what.

3
  • 1
    I find this approach lacking because defining a profile on your test will remove the option to adjust this on the fly via -Dspring.profiles.active=... in CI and other environments which might need other configs that wou might not want to override via -D as this becomes very tedious. After all spinning up spring context should only be needed for integration tests and those are likely to depend on external resources which are different for the environements they run in.
    – elonderin
    Commented Sep 29, 2021 at 15:25
  • 2
    Hey @elonderin, thanks for your comment. If there are configurations that are common to all, i plug them in application.properties. Thereafter, if i develop on local and doing test, spring.profiles.active=local, test. If i am on pre-prod, it becomes spring.profiles.active=pre-prod, test. Is this what you wanted? Commented Sep 30, 2021 at 5:37
  • 2
    This should be the accepted answer. Apparently, test/application.properties doesn't override main/application.properties. Commented Feb 10, 2022 at 4:27
18

TLDR:

So what I did was to have the standard src/main/resources/application.properties and also a src/test/resources/application-default.properties where i override some settings for ALL my tests.

For power-developers:

In order to change/use even more easily different spring profiles, I have a now an application-default.yaml that declares the profiles I want to use. This file is not committed, so that each developer may choose his way of activating profiles and needs (e.g. feature) he/she is working on.

spring:
  profiles:
    include:
      - local
      - devlocal
      - wip
#      - kafka@docker

---
spring.profiles: wip
# ... overriding properties 

Whole Story

I ran into the same problem and was not using profiles either so far. It seemed to be bothersome to have to do it now and remember declaring the profile -- which can be easily forgotten.

The trick is, to leverage that a profile specific application-<profile>.properties overrides settings in the general profile. See https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties.

1
11

If you're using Spring 5.2.5 and Spring Boot 2.2.6 and want to override just a few properties instead of the whole file. You can use the new annotation: @DynamicPropertySource

@SpringBootTest
@Testcontainers
class ExampleIntegrationTests {

    @Container
    static Neo4jContainer<?> neo4j = new Neo4jContainer<>();

    @DynamicPropertySource
    static void neo4jProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.data.neo4j.uri", neo4j::getBoltUrl);
    }
}
2
  • 2
    This should be the top answer. Overriding properties from tests very often needs dynamic values, and just switching to another property file as the other answers won't cut it. Note: The @Testcontainers annotation is not required for this to work. Commented Mar 22, 2022 at 14:14
  • 1
    This doesn't work when not using Test containers
    – user16422658
    Commented Apr 20, 2022 at 21:09
3

I think you can also use this:

@TestPropertySource(properties = "spring.config.additional-location=classpath:application-test.yml")

when custom config locations are configured by using spring.config.additional-location, they are used in addition to the default locations.

The file will have precedence

Please refer here for more details.

1
  • This worked for me, very well. @TestPropertySource(properties = "spring.config.additional-location=file:/Users/..")
    – techsavvy
    Commented Jul 4, 2022 at 15:42
3

This workes for me:

My Test:

@SpringBootTest
@TestPropertySource(properties = "spring.config.additional-location=classpath:application-test.yml")
class EngineApplicationTests {
    @Test
    void contextLoads() {
    }
}

My versions:

plugins {
    id 'org.springframework.boot' version '2.7.1'
    id 'io.spring.dependency-management' version '1.0.12.RELEASE'
    id 'java'
}

group = 'com.kubemachine'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

ext {
    set('springCloudVersion', "2021.0.3")
}

The only test dependency in my gradle file:

testImplementation 'org.springframework.boot:spring-boot-starter-test'

I also have this in my build.gradle file:

test {
    useJUnitPlatform()
}

and two properties file:

  • src/main/resources/application.yml
  • src/test/resources/application-test.yml

And in this setup application-test.yml definitely ONLY overrides the values in application.yml. I don't have to repeat the property values from application.yml in application-test.yml. application-test.yml really extends application.yml.

1

Otherwise we may change the default property configurator name, setting the property spring.config.name=test and then having class-path resource src/test/test.properties our native instance of org.springframework.boot.SpringApplication will be auto-configured from this separated test.properties, ignoring application properties;

Benefit: auto-configuration of tests;

Drawback: exposing "spring.config.name" property at C.I. layer

ref: http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

spring.config.name=application # Config file name

3
  • 6
    Ignoring application.properties is not an option for me as I only want to override some of the original configuration values in the test.
    – FrVaBe
    Commented Nov 10, 2016 at 12:14
  • I've been looking for a way to have a single test that doesn't load the src/main/resources/application.properties and this is it. Create a file: src/test/resources/empty.properties and add the annotation to the test(s) that should ignore the main properties. @TestPropertySource(properties="spring.config.name=empty")
    – rvertigo
    Commented Feb 22, 2019 at 0:50
  • 1
    How to set a specific property value for each junit test method?
    – Nicolas
    Commented Mar 10, 2020 at 16:05
1
I just configured min as the following :

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console


# changing the name of my data base for testing
spring.datasource.url= jdbc:h2:mem:mockedDB
spring.datasource.username=sa
spring.datasource.password=sa



# in testing i don`t need to know the port

#Feature that determines what happens when no accessors are found for a type
#(and there are no annotations to indicate it is meant to be serialized).
spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false`enter code here`
1

Setup

Using

  • properties declared with .yaml file-ending
  • Spring-Boot 2.7
  • and multiple .yaml files in the classpath

Problem

I noticed that the precedence of @TestPropertySource(locations) was not applied as it would be with .properties files.

The problem I was having was, that Spring kept loading all .yaml properties (especially those from production) and overriding the properties meant for the tests with the values specified for prod. (sigh)

Solution

We come up with the workaround of overwriting the config-scraping mechanism by specifying just my application-test.yaml as the only properties used like so:

@TestPropertySource(properties = "spring.config.location=classpath:/application-test.yaml")

Alternative solution

As mentioned above: with .properties files everything works as expected.

Another solution would be to transpile the .yaml to .properties.

Here is a handy online converter: https://mageddo.com/tools/yaml-converter (note its inability to cope with comments)

0

You can create a spring.factories file in src/test/resources/META-INF and a EnvironmentPostProcessor Implementation class in src/test/java.
spring.factories like

# Environment Post Processors
org.springframework.boot.env.EnvironmentPostProcessor=\
com.example.test.YourTestPropertiesConfig

YourTestPropertiesConfig.java like

package com.example.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

import java.util.HashMap;
import java.util.Map;

public class YourTestPropertiesConfig implements EnvironmentPostProcessor {
    private static final Map<String, Object> testProperties = new HashMap<>();
    private static final Set<String> testPropertiesFile = new HashSet<>();

    static {
    //Add the properties you need to take effect globally in the test directly here.
        testProperties.put("spring.jackson.time-zone", "GMT");
        testPropertiesFile.add("classpath:test.properties");
    }

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        environment.getPropertySources().addFirst(new MapPropertySource("TestProperties", testProperties));
        for (String location : testPropertiesFile) {
            try {
                environment.getPropertySources().addFirst(new ResourcePropertySource(location));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void addProperty(String key, Object value) {
        testProperties.put(key, value);
    }

    public static void addProperty(String location) {
        testPropertiesFile.add(location);
    }
}
0

If you really want/have to use System.setProperties(...) then use a Junit extension and annotate the test class:

...
@ExtendWith(MyBeforeAllCallback.class)
public SomeTestClass ...

and use the constructor of the callback to set the system properties.

public MyBeforeAllCallback implements BeforeAllCallback {
    public MyBeforeAllCallback() {
        // wicket 9 workaround for java 17 / cglib issue.
        System.setProperty("wicket.ioc.useByteBuddy", "true");
        // ... whatever you want ...
        System.setProperty("whatever", "you need it badly");
    }
    void beforeAll(ExtensionContext context) {
        // ... empty
    }
}
-1

You can also create a application.properties file in src/test/resources where your JUnits are written.

3
  • How does this help? ^^ Commented Feb 19, 2020 at 7:05
  • 1
    This is what he DOESN'T wants...
    – Ran
    Commented Sep 30, 2021 at 7:05
  • Thanks I had made application-test.properties in test/resources folder - renamed it to application.properties and it worked Commented Feb 28, 2023 at 6:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.