如何 运行 在 Gradle 中测试 JUnit 5 和 JUnit 4 套件?

How to run JUnit 5 and JUnit 4 test suites in Gradle?

我的代码中有两种类型的测试,以 UnitTest 和 IntegrationTest 结尾。当然,有一些遗留的 JUnit 4 测试和应该用 JUnit 5 编写的新测试。

我想要的:

UnitTestSuite 和 IntegrationTestSuit classes 可能是 运行 来自 IDE (IntelliJ IDEA),它们每个都有 class 过滤器测试的名称结尾。我还想要两个不同的 gradle 任务,每个任务都 运行 他们自己的一组测试(理想情况下基于套装,或者至少也基于 class 名称)。

我尝试过的:

此测试套件在 IDE 中运行良好,据我所知,它应该 运行 JUnit 4 和 JUnit 5 测试。但是,这种方法似乎更像是一种解决方法,而不是实际的套件支持。

@RunWith(JUnitPlatform.class)
@IncludeClassNamePatterns({ "^.*UnitTest$" })
public class UnitTestSuite {
}

我还创建了这个 Gradle 任务,但它没有 运行 任何测试对我说:

WARNING: Ignoring test class using JUnitPlatform runner

test { Test t ->

    useJUnitPlatform()

    include "UnitTestSuite.class"
}

运行 JUnit 4 和 JUnit 5 测试是否有解决方案,按名称从 IDE 和 Gradle 任务中筛选(收集到套装中)?

在 Gradle 中,您可以配置多个 test 任务,一个用于 JUnit 4,一个用于 JUnit 5。

我在 Spring 框架构建中正是这样做的。请参阅 spring-test.gradle 中的 testJUnitJupitertest 任务。

task testJUnitJupiter(type: Test) {
    description = "Runs JUnit Jupiter tests."
    useJUnitPlatform {
        includeEngines "junit-jupiter"
        excludeTags "failing-test-case"
    }
    filter {
        includeTestsMatching "org.springframework.test.context.junit.jupiter.*"
    }
    reports.junitXml.destination = file("$buildDir/test-results")
    // Java Util Logging for the JUnit Platform.
    // systemProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager")
}

test {
    description = "Runs JUnit 4 tests."
    dependsOn testJUnitJupiter, testNG
    useJUnit()
    scanForTestClasses = false
    include(["**/*Tests.class", "**/*Test.class"])
    exclude(["**/testng/**/*.*", "**/jupiter/**/*.*"])
    reports.junitXml.destination = file("$buildDir/test-results")
}

您当然可以根据需要命名和配置它们。

有一些注意事项的替代选项是 运行 使用 JUnit 5 进行 JUnit 4(甚至 3)测试。为此,您需要在 运行time 类路径中使用老式引擎,如下所示:

def junit5Version = "5.7.0"
dependencies {
    // other deps
    testImplementation "org.junit.jupiter:junit-jupiter:${junit5Version}"
    testRuntimeOnly "org.junit.vintage:junit-vintage-engine:${junit5Version}"
}

这也适用于 IntelliJ IDEA。

有关如何使 JUnit 4 的其他一些功能与 JUnit 5 一起工作的源代码和进一步说明位于此处:https://junit.org/junit5/docs/current/user-guide/#migrating-from-junit4-running