1

At times, we want to override a property in a Spring application.properties file when we're running unit tests or an application.

Assume gradle manages the builds, and consider this test module, in MinimalValueTest.java.

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ActiveProfiles;

@SpringBootTest
@ActiveProfiles("test")
public class MinimalValueTest {

    @Value("${test.property}")
    String testProperty;

    @Test
    public void test() {
      Assertions.assertTrue(testProperty != null);
      // Support a test that changes the value of test.property at the command line to "property_set_by_override_at_the_command_line"
      // (Unfortunately, org.junit.jupiter version 5 doesn't support this directly.)
      Boolean oneOfTheExpectedValues = (testProperty.equals("a_test_property") ||
                                        testProperty.equals("property_set_by_override_at_the_command_line"));
      Assertions.assertTrue(oneOfTheExpectedValues);
    }

}

This test references this property defined in the src/test/resources/application.properties file:

test.property=a_test_property

What gradle command can be used to override this value of test.property?

Several existing SO questions try, but fail, to solve this problem: Override default Spring-Boot application.properties settings in Junit Test, Problems passing system properties and parameters when running Java class via Gradle, and Passing system properties into Spring Boot from Gradle.

Arthur
  • 525
  • 7
  • 18

2 Answers2

2

Environment variables will override any properties defined in your application*.[properties|yml]. You can read the property resolution order in the Externalized Configuration section of the Core Features documentation of Spring Boot.

Overriding properties with environment variables is pretty straightforward; you just need to follow the convention.

  • Replace dots (.) with underscores (_).
  • Remove any dashes (-).
  • Convert to uppercase.

To override that particular environment variable on a mac/linux/unix, export it (following the above convention).

export TEST_PROPERTY=a_test_property

When your tests run, this will be the property that the property resolver will expose.

Arthur
  • 525
  • 7
  • 18
lane.maxwell
  • 5,002
  • 1
  • 20
  • 30
0

Use @ActiveProfiles("test") on the test to enable the "test" profile. Then, the property can be set in application–test.properties.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80