我们刚刚将单元测试移植到 JUnit5。意识到这仍然是相当早期的采用,谷歌上几乎没有任何提示。
最具挑战性的是为我们在 jenkins 上使用的 Junit5 测试获取 jacoco 代码覆盖率。因为这花了我几乎一天的时间才弄清楚,所以我想我分享一下。尽管如此,如果您知道更好的解决方案,我很有兴趣知道!
buildscript {
dependencies {
// dependency needed to run junit 5 tests
classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.0-M2'
}
}
// include the jacoco plugin
plugins {
id 'jacoco'
}
dependencies {
testCompile "org.junit.jupiter:junit-jupiter-api:5.0.0-M2"
runtime "org.junit.jupiter:junit-jupiter-engine:5.0.0-M2"
runtime "org.junit.vintage:junit-vintage-engine:4.12.0-M2"
}
apply plugin: 'org.junit.platform.gradle.plugin'
那么问题似乎是 org.junit.platform.gradle.plugin 中定义的 junitPlatformTest 也被定义了
在 gradle 生命周期阶段的后期,因此解析脚本时未知。
为了仍然能够定义观察 junitPlatformTest 任务的 jacoco 任务,需要进行以下修改。
tasks.whenTaskAdded { task ->
if (task.name.equals('junitPlatformTest')) {
System.out.println("ADDING TASK " + task.getName() + " to the project!")
// configure jacoco to analyze the junitPlatformTest task
jacoco {
// this tool version is compatible with
toolVersion = "0.7.6.201602180812"
applyTo task
}
// create junit platform jacoco task
project.task(type: JacocoReport, "junitPlatformJacocoReport",
{
sourceDirectories = files("./src/main")
classDirectories = files("$buildDir/classes/main")
executionData task
})
}
}
最后需要配置junitPlatform插件。以下代码允许命令行配置应运行的 junit 5 标签:
您可以通过运行以下命令来运行带有“unit”标签的所有测试:
gradle clean junitPlatformTest -PincludeTags=unit
您可以使用以下命令运行缺少单位和整数标记的所有测试
gradle clean junitPlatformTest -PexcludeTags=unit,integ
如果未提供标签,则将运行所有测试(默认)。
junitPlatform {
engines {
include 'junit-jupiter'
include 'junit-vintage'
}
reportsDir = file("$buildDir/test-results")
tags {
if (project.hasProperty('includeTags')) {
for (String t : includeTags.split(',')) {
include t
}
}
if (project.hasProperty('excludeTags')) {
for (String t : excludeTags.split(',')) {
exclude t
}
}
}
enableStandardTestTask false
}