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.