我有一个 Spring-Boot 应用程序,其中默认属性设置在类路径 (src/main/resources/application.properties) 中的 application.properties
文件中。
我想用 test.properties
文件 (src/test/resources/test.properties) 中声明的属性覆盖我的 JUnit 测试中的一些默认设置
我通常有一个专门的配置类用于我的 Junit 测试,例如
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 {
}
我首先认为在 TestConfig 类中使用 @PropertySource("classpath:test.properties")
可以解决问题,但是这些属性不会覆盖 application.properties 设置(请参阅 Spring-Boot Reference Doc - 23. Externalized Configuration )。
然后我在调用测试时尝试使用 -Dspring.config.location=classpath:test.properties
。那是成功的——但我不想为每个测试执行设置这个系统属性。因此我把它放在代码中
@Configuration
@Import(CoreConfig.class)
@EnableAutoConfiguration
public class TestConfig {
static {
System.setProperty("spring.config.location", "classpath:test.properties");
}
}
不幸的是,这又没有成功。
关于如何使用 --- 覆盖 JUnit 测试中的 test.properties
application.properties
设置,必须有一个简单的解决方案,我一定忽略了。
原文由 FrVaBe 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用
@TestPropertySource
覆盖application.properties
中的值。从它的javadoc:例如: