如何通过Gradle命令临时覆盖Spring测试中application.properties属性?
如何用Gradle命令覆盖Spring测试中的application.properties属性
我们在运行单元测试或Spring应用时,有时需要覆盖application.properties文件中的属性。假设使用Gradle管理构建,现有测试类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.test.context.ActiveProfiles; @SpringBootTest @ActiveProfiles("test") public class MinimalValueTest { @Value("${test.property}") String testProperty; @Test public void test() { Assertions.assertTrue(testProperty != null); // 支持通过命令行将test.property的值改为"property_set_by_override_at_the_command_line" // (遗憾的是JUnit 5本身不直接支持这种方式) Boolean oneOfTheExpectedValues = (testProperty.equals("a_test_property") || testProperty.equals("property_set_by_override_at_the_command_line")); Assertions.assertTrue(oneOfTheExpectedValues); } }
该测试引用src/test/resources/application.properties文件中定义的属性:
test.property=a_test_property
解决方案
要覆盖test.property的值,直接通过Gradle命令行传递系统属性即可——Spring会优先读取系统属性来覆盖配置文件中的值。执行以下命令:
./gradlew test -Dtest.property=property_set_by_override_at_the_command_line
如果需要在构建脚本中做更灵活的配置,可以在build.gradle中添加test任务的系统属性传递配置:
test { // 读取命令行传入的系统属性,没有则用默认值 systemProperty 'test.property', System.getProperty('test.property', 'a_test_property') }
配置后依然用上述命令行方式运行测试即可生效。
内容的提问来源于stack exchange,提问作者Arthur
相关产品推荐
相关产品推荐

