Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access gradle parameter in Java code

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.

like image 712
God_Father Avatar asked Jun 29 '16 16:06

God_Father


People also ask

How do you pass arguments to a gradle task?

If the task you want to pass parameters to is of type JavaExec and you are using Gradle 5, for example the application plugin's run task, then you can pass your parameters through the --args=... command line option. For example gradle run --args="foo --bar=true" .

How do you pass JVM arguments in gradle?

Try to use ./gradlew -Dorg. gradle. jvmargs=-Xmx16g wrapper , pay attention on -D , this marks the property to be passed to gradle and jvm. Using -P a property is passed as gradle project property.

How do I open the gradle command line?

Press ⌃⌃ (macOS), or Ctrl+Ctrl (Windows/Linux), type "gradle" followed by the gradle task name or names. We can, of course, run Gradle commands from the terminal window inside IntelliJ IDEA. Open this with ⌥F12 (macOS), or Alt+F12 (Windows/Linux).


1 Answers

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.

like image 51
Opal Avatar answered Sep 20 '22 16:09

Opal