您可以在支持 Gradle 的 IDE 中打开此示例。

此示例展示了如何使用 JaCoCo 聚合多个 Java 子项目的代码覆盖率。通过一个独立的工具项目来指定要包含用于聚合的子项目,jacoco-report-aggregation 插件提供了此功能。

此示例中的项目包含三个“代码”子项目:applicationlistutilities。这三个项目都应用了 jacoco 插件,并且 application 通过其实现配置使用了 listutilities。第四个子项目 code-coverage-report 是用于收集覆盖率结果的独立工具项目。

测试报告聚合插件目前不支持 com.android.application 插件。
code-coverage-report/build.gradle.kts
plugins {
    base
    id("jacoco-report-aggregation")
}

repositories {
    mavenCentral()
}

dependencies {
    jacocoAggregation(project(":application")) (1)
}

reporting {
    reports {
        val testCodeCoverageReport by creating(JacocoCoverageReport::class) { (2)
            testSuiteName = "test"
        }
    }
}

tasks.check {
    dependsOn(tasks.named<JacocoReport>("testCodeCoverageReport")) (3)
}
code-coverage-report/build.gradle
plugins {
    id 'base'
    id 'jacoco-report-aggregation'
}

repositories {
    mavenCentral()
}

dependencies {
    jacocoAggregation project(':application') (1)
}

reporting {
    reports {
        testCodeCoverageReport(JacocoCoverageReport) { (2)
            testSuiteName = "test"
        }
    }
}

tasks.named('check') {
    dependsOn tasks.named('testCodeCoverageReport', JacocoReport) (3)
}

独立项目应用了 jacoco-report-aggregation,但如果不存在 jvm-test-suite 插件,则需要额外的配置。

在此场景下,需要进行另外两项设置:

1 使用 jacocoAggregation 配置声明依赖项
2 定义一个类型为 JacocoCoverageReport 的报告,该报告收集来自单元测试套件的覆盖率数据
3 可选:将 JaCoCo 聚合报告生成作为 'check' 生命周期阶段的一部分

报告聚合逻辑不会自动检查所有子项目以聚合覆盖率数据。相反,jacocoAggregation 配置的直接和传递项目依赖项被选择用于潜在的聚合。

用户还必须声明一个或多个类型为 JacocoCoverageReport 的报告。每个报告实例指定一个 testType 属性,用于匹配生成覆盖率数据的测试套件。会为每个用户定义的报告合成一个 JacocoReport 任务,并执行聚合。调用此任务将导致在 jacocoAggregation 配置的依赖项目中执行测试。

运行测试并生成报告

$ ./gradlew testCodeCoverageReport

BUILD SUCCESSFUL
25 actionable tasks: 25 executed

XML 和 HTML 报告现在可以在 code-coverage-report/build/reports/jacoco/testCodeCoverageReport 目录下找到。

更多信息,请参阅Java 项目中的测试章节