Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle task check if property is defined

I have a Gradle task that executes a TestNG test suite. I want to be able to pass a flag to the task in order to use a special TestNG XML suite file (or just use the default suite if the flag isn't set).

gradle test

... should run the default standard suite of tests

gradle test -Pspecial

... should run the special suite of tests

I've been trying something like this:

test {
    if (special) {
        test(testng_special.xml);
    }
    else {
        test(testng_default.xml);
    }
}

But I get a undefined property error. What is the correct way to go about this?

like image 287
user2506293 Avatar asked Jul 08 '15 19:07

user2506293


People also ask

Where Gradle tasks are defined?

You define a Gradle task inside the Gradle build script. You can define the task pretty much anywhere in the build script. A task definition consists of the keyword task and then the name of the task, like this: task myTask. This line defines a task named myTask .


3 Answers

if (project.hasProperty('special'))

should do it.

Note that what you're doing to select a testng suite won't work, AFAIK: the test task doesn't have any test() method. Refer to https://discuss.gradle.org/t/how-to-run-acceptance-tests-with-testng-from-gradle/4107 for a working example:

test {
    useTestNG {
        suites 'src/main/resources/testng.xml'
    }
}
like image 163
JB Nizet Avatar answered Oct 19 '22 07:10

JB Nizet


This worked for me:

test {
    if (properties.containsKey('special')) {
        test(testng_special.xml);
    }
    else {
        test(testng_default.xml);
    }
}
like image 2
Noelia Avatar answered Oct 19 '22 06:10

Noelia


Here are 3 solutions for Kotlin DSL (build.gradle.kts):

val prop = project.properties["myPropName"] ?: "myDefaultValue"
val prop = project.properties["myPropName"] ?: error("Property not found")
if (project.hasProperty("special")) {
    val prop = project.properties["myPropName"]
}

Note that you can omit the project. prefix as it is implicit in Gradle build files.

like image 1
Mahozad Avatar answered Oct 19 '22 07:10

Mahozad