【问题标题】:How to give System property to my test via Kotlin Gradle and -D如何通过 Kotlin Gradle 和 -D 为我的测试提供系统属性
【发布时间】:2019-10-30 21:50:21
【问题描述】:

当我在 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 文件中无法识别。

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

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

【问题讨论】:

    标签: java gradle kotlin spock


    【解决方案1】:

    您的链接问题的答案可以 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"))
    }
    

    【讨论】:

      【解决方案2】:

      本示例演示了将系统属性传递给 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>)
      }
      

      【讨论】:

        猜你喜欢
        • 2014-02-19
        • 2017-09-24
        • 1970-01-01
        • 1970-01-01
        • 2013-12-27
        • 2010-10-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多