简体   繁体   中英

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

When I run a test in Gradle I would like to pass some properties:

./gradlew test -DmyProperty=someValue

So in my Spock test I will use to retrieve the value:

def value = System.getProperty("myProperty")

Im using the kotlin gradle dsl. When I try and use 'tasks.test' as in this documentation: https://docs.gradle.org/current/userguide/java_testing.html#test_filtering

'test' is not recognised in my build.gradle.kts file.

I'm assuming I would need to use something similar to the answer in the post below but it is not clear how it should be done in the using the gradle kotlin DSL.

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

The answers from your linked question are translatable 1:1 to the kotlin DSL. Here is a full example using 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"))
}

This example demos three ways of passing system properties to the junit test. Two of them specifies the system properties one at a time. The last avoids having to forward declare each system property by taking all system properties available to the gradle runtime and passes them to the junit test harness.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM