如何在Java代码中访问gradle参数 [英] How to access gradle parameter in Java code
问题描述
我有一些java的经验,我是gradle的新手,我加入了一个项目,我必须修改gradle文件。
这是我的 build.gradle
file
apply plugin:'java'
apply插件:'idea'
sourceCompatibility = 1.5
version ='1.0'
dependencies {
testCompile'org.testng:testng:6.9.10',
'org.seleniumhq.selenium:selenium-java:2.53.0'
}
test {
useTestNG()
testLogging.showStandardStreams = true
$ / code>
然后使用以下命令从mac终端运行我的测试套件
./ build test
我想传递一个名为 environment $ c的参数$ c>
根据此参数的值,我需要配置我的url并为该环境运行测试。像 ./ build test环境= dev
或 ./ build test environment = qa
$ b
在我的java代码中,我会做这样的事情。 '){
url =my dev url;
user =我的开发者用户名
} else if(env =='qa'){
url =my qa url;
user =我的qa用户名
}
如何通过这个参数在终端?
我在代码中使用这个参数的一小段代码会很有帮助(我的java代码没有main方法)。
注意:我已经使用过一个属性文件并实现了这种行为,但我的团队不想在代码中进行更改以设置环境。所以我不得不放弃这些改变。
从命令行到gradle,您可以使用系统属性或项目属性。它可以是:
./ gradlew test -Denv = dev
或
./ gradle test -Penv = dev
上面的属性现在可以在 build.gradle
,你需要将它们传递给测试,它必须使用系统属性来完成:
test {
systemProperty'env',System.properties ['env']?:'dev'
}
$ b从命令行或者:
test {
systemProperty'env',project。 hasProperty('env')? project.env:'dev'
}
在测试类中使用:
System.getProperty(env)
以获得您需要的值。
I have some experience with java and I am new to gradle and I joined a project in which I have to modify the gradle file.
Here is my build.gradle
file
apply plugin: 'java'
apply plugin: 'idea'
sourceCompatibility = 1.5
version = '1.0'
dependencies {
testCompile 'org.testng:testng:6.9.10',
'org.seleniumhq.selenium:selenium-java:2.53.0'
}
test {
useTestNG()
testLogging.showStandardStreams = true
}
I then run my test suite using the following command from the mac terminal
./build test
I want to pass a parameter named environment
Based on this value of this parameter, I need to configure my urls and run tests for that environment. Something like ./build test environment=dev
or ./build test environment=qa
And in my java code I would do something like this
if(env == 'dev') {
url = "my dev url";
user = "my dev user name"
} else if(env == 'qa') {
url = "my qa url";
user = "my qa user name"
}
How can I pass this parameter in the terminal ? A small snippet of how I can use this parameter in my code would be of great help (my java code does not have a main method).
Note: I have already used a property file and achieved this behaviour, but my team does not want to make changes in code to set the environment. So I had to discard those changes.
From command line to gradle you can use system properties or project properties. It will be either:
./gradlew test -Denv=dev
or
./gradle test -Penv=dev
The properties above can be now read in a build.gradle
, you need to pass them to tests as well, it must be done with system properties so:
test {
systemProperty 'env', System.properties['env'] ?: 'dev'
}
for system properties from command line or:
test {
systemProperty 'env', project.hasProperty('env') ? project.env : 'dev'
}
In test classes use just:
System.getProperty("env")
to get the value you need.
这篇关于如何在Java代码中访问gradle参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!