使用 Gradle 将多个 JaCoCo .exec 文件聚合到单个 Coverage 报告中

问题描述

情况 我正在开发一个运行良好的 Spring Boot 应用程序,但构建-测试周期太长,在普通开发环境中不实用。

因此,我最近决定拆分单元测试和集成测试。集成测试基于 Cucumber,而单元测试是普通的 JUnit 5 测试。

为此,我使用了 Gradle 插件 org.unbroken-dome.test-sets,它很好地创建了相关的 sourceSets 等。

testSets {
    intTest { dirName = 'int-test' }
}

一切正常,我的测试按预期执行。当我进行构建时仍然会执行单元测试,而当我调用 `gradlew intTest' 时会执行集成测试。这是设计使然,因为我不想一直执行所有测试。

运行测试后,我还有一个 jacoco/test.exec 文件一个 jacoco/inttest.exec 文件。一切都是设计和测试集插件所宣传的。

问题 这是我的问题。当我的所有测试仍在 test-SourceSet 中时,因此在拆分之前且仅生成 test.exec 文件时,JaCoCo 报告的覆盖率约为 75%。但是现在我已经拆分了测试并拥有 test.execintTest.exec 文件,JaCoCo 只报告了 15% 的覆盖率,考虑到我的单元测试和集成测试的范围,这是正确的。

问题 如何让 JaCoCo 同时使用 test.execintTest.exec 文件来报告覆盖率并允许覆盖率验证任务再次考虑两者?

相关代码 下面是一些相关的代码: jacoco.gradle

apply plugin: 'java'
apply plugin: 'jacoco'

// -----------------------------------------------------------
//
// JaCoCo
dependencies {
    implementation "org.jacoco:org.jacoco.agent:${jacocoToolVersion}:runtime"
}

jacoco {
    toolVersion = "${jacocoToolVersion}"
}

jacocoTestReport {
    dependsOn test
    reports {
        xml.enabled false
        csv.enabled true
        html.destination file("${buildDir}/reports/jacoco/Html")
        csv.destination file("${buildDir}/reports/jacoco/jacoco.csv")
    }
}

jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = minCodeCoverage
            }
        }
    }
}

check.dependsOn jacocoTestCoverageVerification

来自 build.gradle 的片段:

tasks.withType(Test) {
    useJUnitPlatform()
    testLogging {
        events "passed","skipped","Failed"
    }
    testLogging.showStandardStreams = true
    reports {
        junitXml.enabled = true
        html.enabled = true
    }
}

testSets {
    intTest { dirName = 'int-test' }
}

intTest.mustRunAfter test
check.dependsOn intTest

test {
    systemProperties System.getProperties()

    finalizedBy jacocoTestReport
}

预先感谢您帮助我或为我指明正确的方向。

解决方法

好的,您知道,一旦您阐明了您的问题,您就知道该用 Google 做什么吗?好吧,经过更多的挖掘,我得到了一些灵​​感,这给了我一个 jacocoTestReport 定义:

jacocoTestReport {
    dependsOn test
    sourceSets sourceSets.main
    executionData fileTree(project.rootDir.absolutePath).include("**/build/jacoco/*.exec")
    reports {
        xml.enabled false
        csv.enabled true
        html.destination file("${buildDir}/reports/jacoco/Html")
        csv.destination file("${buildDir}/reports/jacoco/jacoco.csv")
    }
}

我犯的错误是我在 jacocoTestCoverageVerification 部分聚合了 exec 文件,而不是 jacocoReport。

因此,将 executionData 部分放在正确的位置,再次给了我正确的覆盖率值。呜呜!!!