从Gradle构建设置一个环境变量

从Gradle构建设置一个环境变量

本文介绍了从Gradle构建设置一个环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的Gradle构建中设置一个环境变量。我在MacOS X(El Capitan)。
该命令是gradle test。



我正在build.gradle中尝试这个:

  task setenv(type:Exec){
commandLineexport,SOME_TEST_VAR = aaa
}
test.dependsOn setenv

,构建失败:


我也尝试过:

  test.doFirst {
ProcessBuilder pb1 = new ProcessBuilder(export SOME_TEST_VAR = some test value)
pb1.start();
}

构建成功。但是,如果我在JUnit测试中检查环境变量,它将失败:

  assertTrue(System.getenv()。containsKey SOME_TEST_VAR)); 

有没有办法从Gradle构建设置环境变量(在build.gradle文件中) ?



更新:



我已经隔离测试:做得到传递,我的测试任务收到一切,无论是systemProperty,环境变量还是jvmArgs。



所以,这里的Gradle本身没什么问题。



当我在真正的项目中尝试时,会出现问题。它使用Spring进行依赖注入。我可能错了,但是Spring框架看起来像在某个地方清除这些值。



该子项目目前正在冻结,我现在无法详细检查我的猜测。

解决方案

对于测试任务,您可以使用,如下所示:

  test {
environmentVAR,val
}

你也可以使用在执行任务中

  task dropDatabase(type:Exec){ 
环境VAR,val
commandLinedoit
}

请注意,使用此方法,环境变量仅在任务期间设置。


I'm trying to set an environment variable from my Gradle build. I'm on MacOS X (El Capitan).The command is "gradle test".

I'm trying this in my build.gradle:

task setenv(type: Exec) {
    commandLine "export", "SOME_TEST_VAR=aaa"
}
test.dependsOn setenv

and the build fails:

I also tried this:

test.doFirst {
    ProcessBuilder pb1 = new ProcessBuilder("export SOME_TEST_VAR=some test value")
    pb1.start();
}

The build succeeds. However, if I check the environment variable in my JUnit test it fails:

assertTrue(System.getenv().containsKey("SOME_TEST_VAR"));

Is there any way to set an environment variable from a Gradle build (in the build.gradle file)?

Update:

I've tested it in isolation: the values do get passed and my test task receives everything, be it a systemProperty, environment variables or jvmArgs.

So, it's nothing wrong with Gradle itself here.

The problem arises when I'm trying it on the real project. It uses Spring for dependency injection. I may be wrong but it looks like the Spring framework purges those values somewhere.

That sub-project is currently being frozen and I can't check my guess in detail right now.

解决方案

For a test task, you can use the environment property like this:

test {
  environment "VAR", "val"
}

you can also use the environment property in an exec task

task dropDatabase(type: Exec) {
    environment "VAR", "val"
    commandLine "doit"
}

Note that with this method the environment variables are set only during the task.

这篇关于从Gradle构建设置一个环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 20:29