【发布时间】:2016-12-17 11:21:35
【问题描述】:
我有一个 Spring Boot gradle 应用程序。当我运行 gradle 构建时,我想针对不同的环境运行。
例如:./gradlew clean build -Dapp.env=QA1。在测试代码中,我想检查这个属性并相应地收集测试数据。我观察到的是属性(app.env)不可用。
构建应该会失败,因为测试会检查系统属性。但构建成功。我也没有在控制台中看到 println 语句。
如果你想克隆 repo:
git 克隆https://SpringDevSeattle@bitbucket.org/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 两种情况下构建都会失败
【问题讨论】:
标签: spring gradle spring-boot spring-test