Gradle 任务检查是否定义了 属性

Gradle task check if property is defined

我有一个执行 testng 测试套件的 gradle 任务。 我希望能够将标志传递给任务,以便使用特殊的 testng xml 套件文件(或者如果未设置标志,则只使用默认套件)。

gradle test

应该运行默认的标准测试套件

gradle test -Pspecial

应该运行特殊测试套件

我一直在尝试这样的事情:

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

但是我得到一个未定义的 属性 错误。正确的做法是什么?

if (project.hasProperty('special'))

应该这样做。

请注意,您对 select testng 套件所做的操作将不起作用,AFAIK:测试任务没有任何 test() 方法。参考 https://discuss.gradle.org/t/how-to-run-acceptance-tests-with-testng-from-gradle/4107 的工作示例:

test {
    useTestNG {
        suites 'src/main/resources/testng.xml'
    }
}

来自Gradle Documentation

-P, --project-prop

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

所以你应该使用:

gradle test -Pspecial=true

在 属性 名称后有一个值

这对我有用:

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