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

7
我在代码中有两种测试类型,以UnitTest和IntegrationTest结尾。当然,还有一些遗留的JUnit 4测试和新的应该使用JUnit 5编写的测试。
我想要的是: 1. UnitTestSuite和IntegrationTestSuit类可以从IDE(IntelliJ IDEA)运行,每个类都有按测试类名结尾的过滤器。 2. 我希望有两个不同的Gradle任务,每个任务运行自己的测试集(最好基于测试套件,或至少基于类名)。
我已经尝试了这个测试套件,它可以从IDE中很好地工作,并且我理解它应该可以运行JUnit 4和JUnit 5测试。但是,似乎这种方法更像是一个解决方法而不是实际的测试套件支持。
@RunWith(JUnitPlatform.class)
@IncludeClassNamePatterns({ "^.*UnitTest$" })
public class UnitTestSuite {
}

我创建了这个Gradle任务,但它没有运行任何测试,并告诉我:

警告:使用JUnitPlatform运行程序时忽略测试类

test { Test t ->

    useJUnitPlatform()

    include "UnitTestSuite.class"
}

那么有没有一种解决方案可以同时运行从IDE和Gradle任务中过滤出来并以套件的形式组合的JUnit 4和JUnit 5测试?

2个回答

6

在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")
}

当然,您可以根据自己的需要对它们进行命名和配置。


是的,在Gradle中将任务拆分为两个是一个好主意,但在这种情况下,我就没有单个Suite类可以直接从IDE运行j4和j5测试了,对吧? - KeLsTaR
不,你不会有一个单一的测试套件“类”,但是你可以在IDE中运行Gradle任务。 - Sam Brannen
2
此外,您还可以引入3个Gradle“test”任务:testJUnit4testJUnitJupitertest,这些任务依赖于前两个。 - Sam Brannen
这是一个有趣的答案,我没有想过。谢谢! - KeLsTaR
你如何管理这些任务的依赖关系?Junit 5将需要与Junit4不同的依赖项。 - heart_coder
1
@heart_coder,这不是问题。JUnit 4和JUnit Jupiter没有任何重叠或冲突的依赖关系。因此,在同一测试类路径中包含它们所有的依赖关系并不是一个问题。 - Sam Brannen

3

另一种选择是使用JUnit 5来运行JUnit 4(甚至3)测试,但这种方法有一些注意事项。为此,您需要在运行时类路径上拥有Vintage引擎,例如:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接