我有一个 Spring Boot Gradle 应用程序。当我运行 gradle 构建时,我想在不同的环境中运行。
例如:./gradlew clean build -Dapp.env=QA1
。在测试代码中,我想检查此属性并相应地收集测试数据。我观察到属性(app.env)不可用。
由于测试检查系统属性,构建应该失败。但构建成功。我也没有在控制台中看到 println 语句。
如果您想克隆存储库:
git 克隆 https://Spr[email protected]/SpringDevSeattle/gs-rest-service.git
这是我的测试代码:
src/test/java/hello/GreetingControllerTests.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@ContextConfiguration(classes={hello.TestConfig.class,hello.AppConfig.class})
@WebAppConfiguration
public class GreetingControllerTests {
@Autowired
TestEnv testEnv;
@Autowired
Status status;
private String env;
@Before
public void init(){
System.out.println(status.getName());
env=testEnv.getEnv();
}
@Test
public void should_fail(){
if (env.equalsIgnoreCase("DEV")){
assertThat(false).isFalse();
}
if (env.equalsIgnoreCase("QA1")){
System.out.println("failing the test");
fail();
}
}
}
src/test/java/hello/TestConfig.java
@Configuration
public class TestConfig {
@Bean
public TestEnv testEnv(){
Properties properties = System.getProperties();
String env = properties.getProperty("app.env");
System.out.println(env);
if (env==null){
env="dev";
}
return new TestEnv(env);
}
}
src/test/java/hello/TestEnv.java
public class TestEnv {
private String env;
public TestEnv(String env){
this.env=env;
}
public String getEnv() {
return env;
}
public void setEnv(String env) {
this.env = env;
}
}
src/main/java/hello/AppConfig.java
@Configuration
public class AppConfig {
@Value("${app.version}")
private String version;
@Value("${app.name}")
private String name;
@Bean
public Status status(){
return new Status(name,version);
}
}
我的最终目标是为基于通过的 -Dapp.env
的测试设置“spring.profiles.active”。但我目前没有看到 gradle run 中拾取的系统属性。
编辑
即使使用./gradlew clean build -Dspring.profiles.active=QA1
,我也看不到它的工作。
测试也随之改变。
@Autowired
Environment envi
@Before
public void init(){
System.out.println("*********-IN THE INIT METHOD **********"); //new line added
System.out.println(status.getName());
env=envi.getActiveProfiles()[0];
}
@Test
public void should_fail(){
if (env.equalsIgnoreCase("DEV")){
assertThat(false).isFalse();
}
if (env.equalsIgnoreCase("QA1")){
System.out.println("failing the test");
fail();
}
}
在 -Dspring.profiles.active=DEV
或 -Dspring.profiles.active=QA1
的情况下构建都会失败
最佳答案
Gradle 在单独的 JVM 中执行测试。因此,在命令行指定的系统属性将在构建 JVM 中使用,并且不会传播到测试 JVM。这样做的目的是为了将测试过程与构建过程隔离。您可以像这样显式指定专门用于测试过程的系统属性。
test {
systemProperty 'key', 'value'
}
或者,您可以简单地将所有系统属性传递给测试进程,这将允许您通过 -D
语法在命令行上指定它们。
test {
systemProperties = System.props
}
关于spring - 系统属性 -Dspring.profiles.active 在 gradle 构建的 spring boot 测试配置中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38884174/