54

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?

mkobit
  • 39,564
  • 9
  • 145
  • 144
user2506293
  • 785
  • 1
  • 6
  • 13

3 Answers3

100
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'
    }
}
JB Nizet
  • 657,433
  • 87
  • 1,179
  • 1,226
  • @user2506293, that's not necessarily enough. You need to both check if project has a property and if **it's set**. – Opal Jul 10 '15 at 09:48
  • This is groovy @Opal - a null results in false, so you don't need to explicitly check that. – th3morg May 14 '16 at 00:58
  • @th3morg Thats wrong, if a property exists but is null, hasProperty(..) will still return true, so you have to use `if (project.hasProperty('special') && project.special)` if you want to check for both existance and not null. – Katharsas Jan 26 '20 at 21:21
  • I like to use: `project.properties["special"] == "true"` – Venryx May 25 '20 at 17:06
2

This worked for me:

test {
    if (properties.containsKey('special')) {
        test(testng_special.xml);
    }
    else {
        test(testng_default.xml);
    }
}
Noelia
  • 2,954
  • 3
  • 16
  • 21
-1

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

Community
  • 1
  • 1
  • using JB Nizet's solution it's not necessary to set the property to true, just to define it – user2506293 Jul 08 '15 at 20:06
  • That's true, because you aren't reading the property value, but just checking if the property exist. Suppose that you were doing the opposite, so instead of `Special` you were using `notSpecial` and you needed a false value for this property in your condition. Using my solution you will not have problems because you will pass `-PnotSpecial=false` using JBNizet's solution instead the value passed was true anyway because the `notSpecial` property exist. – Alex Cortinovis Jul 08 '15 at 21:12