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

2ha*_*ems 6 java gradle spock kotlin

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

./gradlew test -DmyProperty=someValue
Run Code Online (Sandbox Code Playgroud)

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

def value = System.getProperty("myProperty")
Run Code Online (Sandbox Code Playgroud)

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

我的build.gradle.kts文件中无法识别“测试” 。

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

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

Chr*_*s K 9

此示例演示了将系统属性传递给 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>)
}
Run Code Online (Sandbox Code Playgroud)


Flo*_*ann 7

您链接的问题的答案可以 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"))
}
Run Code Online (Sandbox Code Playgroud)