Gradle task check if property is defined

PropertiesGradleTaskTestng

Properties Problem Overview


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?

Properties Solutions


Solution 1 - Properties

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'
    }
}

Solution 2 - Properties

This worked for me:

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

Solution 3 - Properties

From Gradle Documentation:

> -P, --project-prop > > Sets a project property of the root project, for example -Pmyprop=myvalue

So you should use:

gradle test -Pspecial=true

with a value after the property name

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2506293View Question on Stackoverflow
Solution 1 - PropertiesJB NizetView Answer on Stackoverflow
Solution 2 - PropertiesNoeliaView Answer on Stackoverflow
Solution 3 - PropertiesAlex CortinovisView Answer on Stackoverflow