Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GRADLE: TestNg - unable to pass -D parameter to java code

I have a Test framework written in Java utilizing TestNg, and built using gradle. I want to pass an 'environment' argument at the command line, which will be used in an Environment class to define domain and server values for specific environments. Using the Gradle documentation and several forum discussions on this issue, I am still unable to get the argument passed as a system property to the framework. I have tried to accomplish this from the 'test' task AND the 'debug' task, to NO avail. A 'println' statement in the task shows that the -Denv parameter is being picked up by gradle, but my attempt to add it to the System properties for the test framework fails.

Execution results in a null reference, with environmentName being set to null.

Can someone identify my error?

command line

.\gradlew debug -Denv=production

build.gradle

test {
    def environment = System.properties["env"]
    println environment
    systemProperties = System.getProperties()
    systemProperties['env'] = environment
    useTestNG()
}

task debug(type: Test) {
//    def environment = System.properties["env"]
//    println environment
//    systemProperties = System.getProperties()
//    systemProperties['env'] = environment
    def groupsToInclude = []
    def groupsToExclude = []

    groupsToInclude.add('under_development')
    useTestNG() {
        groupsToInclude.each { String group -> includeGroups group }
        groupsToExclude.each { String group -> excludeGroups group }
    }
}

java class

import com.sun.javafx.runtime.SystemProperties;

public class Environment {

    private static EnvironmentDefinition environment;

    private Environment() {
    }

    public static EnvironmentDefinition getInstance() {
        if (environment == null) {
            String environmentName = SystemProperties.getProperty("env");
            // environmentName = environmentName == null ? "production" : environmentName;
            switch (environmentName) {
                default:
                    Environment.environment = ProductionEnvironment.getInstance();
            }
        }
        return environment;
    }
}
like image 571
CStockton Avatar asked Jun 22 '26 23:06

CStockton


2 Answers

It all works well, please have a look at the demo I prepared. Mind the fact that you cannot set the system property to null value - it might be a problem as well.

like image 55
Opal Avatar answered Jun 24 '26 11:06

Opal


"It's System, you dummy...not SystemProperties!...

Isn't it always the most simple oversights that cause the most trouble?

After cloning Opal's solution along side mine, and bringing them into alignment one step at a time, I noticed that in the java code my reference was to SystemProperties.getProperty(), rather than System.getProperty().

like image 26
CStockton Avatar answered Jun 24 '26 13:06

CStockton