Search code examples
javagradlekotlinspock

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


Solution

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