需要使用 spring 配置文件通过 gradle 运行测试。
gradle clean build
我添加了任务:
task beforeTest() {
doLast {
System.setProperty("spring.profiles.active", "DEV")
}
}
test.dependsOn beforeTest
我的测试定义是:
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("TestProfile")
public class SomeTest {
但是这个结构对我不起作用。
Gradle 运行测试。
我认为您想要在运行时/测试 JVM 中设置系统属性,但您在构建时 JVM(即 Gradle 守护进程)中错误地设置了系统属性。
参见 Test.systemProperty(String, Object)
例如:
test {
systemProperty 'spring.profiles.active', 'DEV'
}
...以及关于您的尝试的另一条注释。请注意,任务有一个
doFirst
和 doLast
方法,因此您不需要为您正在尝试的任务创建单独的任务。
这对我有用:
test {
systemProperty 'spring.profiles.active', 'ci'
}
现在,当我执行
gradlew test
时,它会使用 ci
配置文件运行。
这对我有用
tasks.withType<Test> {
systemProperty("spring.profiles.active", "DEV")
}
使用 gradle,
-D
标志允许传递 gradle 系统属性变量:
./gradlew test -Dspring.profiles.active=test,dev
因此
test
然后 dev
将按各自的顺序加载。
https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.profiles
想知道这是不是一个很晚的回复?但我也遇到过类似的问题。
所以最后我发现@Profile需要位于src/main/*文件夹中。 Gradle test 似乎优先于 /src/main 而不是 /src/test。这样我的@Profile(“test”)就被转换成了@Profile(“!test”)。构建的 gradle 中没有添加 spring.profiles.active 。