如何通过 Kotlin Gradle 和 -D 为我的测试提供系统 属性

How to give System property to my test via Kotlin Gradle and -D

当我 运行 在 Gradle 中进行测试时,我想传递一些属性:

./gradlew test -DmyProperty=someValue

所以在我的 Spock 测试中,我将使用检索值:

def value = System.getProperty("myProperty")

我正在使用 kotlin gradle dsl。当我像本文档中那样尝试使用 'tasks.test' 时: https://docs.gradle.org/current/userguide/java_testing.html#test_filtering

'test' 在我的 build.gradle.kts 文件中无法识别。

我假设我需要使用类似于下面 post 中的答案的东西,但不清楚在使用 gradle kotlin DSL 时应该如何完成。

How to give System property to my test via Gradle and -D

您的链接问题的答案可以1:1 翻译成 kotlin DSL。这是使用 junit5 的完整示例。

dependencies {
    // ...
    testImplementation("org.junit.jupiter:junit-jupiter:5.4.2")
    testImplementation(kotlin("test-junit5"))
}

tasks.withType<Test> {
    useJUnitPlatform()

    // Project property style - optional property.
    // ./gradlew test -Pcassandra.ip=xx.xx.xx.xx
    systemProperty("cassandra.ip", project.properties["cassandra.ip"])

    // Project property style - enforced property.
    // The build will fail if the project property is not defined.
    // ./gradlew test -Pcassandra.ip=xx.xx.xx.xx
    systemProperty("cassandra.ip", project.property("cassandra.ip"))

    // system property style
    // ./gradlew test -Dcassandra.ip=xx.xx.xx.xx
    systemProperty("cassandra.ip", System.getProperty("cassandra.ip"))
}

此示例演示了将系统属性传递给 junit 测试的三种方法。其中两个一次指定一个系统属性。最后一个避免了通过获取 gradle 运行时可用的所有系统属性并将它们传递给 junit 测试工具来转发声明每个系统 属性。

tasks.withType<Test> {
    useJUnitPlatform()

    // set system property using a property specified in gradle
    systemProperty("a", project.properties["a"])

    // take one property that was specified when starting gradle
    systemProperty("a", System.getProperty("a"))

    // take all of the system properties specified when starting gradle
    // which avoids copying each property over one at a time
    systemProperties(System.getProperties().toMap() as Map<String,Object>)
}