【问题标题】:Run gradle test from another gradle task从另一个 gradle 任务运行 gradle test
【发布时间】:2020-07-09 08:39:48
【问题描述】:

我创建了使用 gradle 构建系统的 Spring Boot 项目。我想通过自定义 gradle 任务运行一个单独的测试类,以便能够在其他任务中依赖它。现在我可以用这段代码来做:

import org.apache.tools.ant.taskdefs.condition.Os

def gradleWrapper = Os.isFamily(Os.FAMILY_WINDOWS) ? 'gradlew.bat' : './gradlew'

task runMyTest(type: Exec) {
    workingDir "$rootDir"
    commandLine gradleWrapper, ':test', '--tests', 'com.example.MyTest'
}

显然,这不是一个非常漂亮的解决方案,因为它会启动一个额外的 Gradle 守护进程。我在另一个解决方案之前尝试过:

task runMyTest(type: Test, dependsOn: testClasses) {
    include 'com.example.MyTest'
}

但它不起作用(不要执行我的测试类)。

UPD:我尝试了另一种解决方案:

task runMyTest(type: Test) {
    filter {
        includeTestsMatching "com.example.MyTest"
    }
}

失败并显示以下错误消息:

Execution failed for task ':runMyTest'.
> No tests found for given includes: [com.example.MyTest](filter.includeTestsMatching)

但是,显然,我的测试存在,因为通过命令行运行测试会产生正确的结果。

UPD2:我在测试任务中错过了useJUnitPlatform()。它在默认测试任务中(由 Spring Boot 初始化程序写入我的 build.gradle),但不在自定义任务中。

【问题讨论】:

    标签: spring gradle junit


    【解决方案1】:

    您可以使用TestFilter 来完成。

    使用includeTestsMatching,您可以指定您的班级。

    如果需要指定单个测试方法,可以使用includeTest "com.example.MyTest", "someTestMethod"

    task runMyTest(type: Test) {
        useJUnitPlatform()
        filter {
            includeTestsMatching "com.example.MyTest"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多