繁体   English   中英

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

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

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

我想要的是:

可以从 IDE (IntelliJ IDEA) 运行的 UnitTestSuite 和 IntegrationTestSuit 类,每个类都有以类名结尾的测试过滤器。 此外,我希望两个不同的 gradle 任务各自运行自己的一组测试(理想情况下基于套装,或者至少基于类名)。

我试过的:

这个测试套件在 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 Framework 构建中正是这样做的。 请参阅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)测试。为此,您需要在运行时类路径上使用老式引擎,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM