从另一个 gradle 任务运行 gradle 测试

kiv*_*ple 0 junit spring gradle

我创建了使用 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'
}
Run Code Online (Sandbox Code Playgroud)

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

task runMyTest(type: Test, dependsOn: testClasses) {
    include 'com.example.MyTest'
}
Run Code Online (Sandbox Code Playgroud)

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

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

task runMyTest(type: Test) {
    filter {
        includeTestsMatching "com.example.MyTest"
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Gio*_*oli 5

您可以使用TestFilter来完成此操作。

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

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

task runMyTest(type: Test) {
    useJUnitPlatform()
    filter {
        includeTestsMatching "com.example.MyTest"
    }
}
Run Code Online (Sandbox Code Playgroud)