您可以在支援 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 專案章節中的測試