您可以使用 IntelliJ 原生匯入器Eclipse Buildship 在 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)
            testType = TestSuiteType.UNIT_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)
            testType = TestSuiteType.UNIT_TEST
        }
    }
}

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

獨立專案套用 jacoco-report-aggregation,但如果 jvm-test-suite 外掛程式不存在,則需要額外的設定。

在此情況下,需要兩個額外的設定步驟

1 使用 jacocoAggregation 設定宣告相依性
2 定義類型為 JacocoCoverageReport 的報告,用於收集單元測試套件的涵蓋率資料
3 選擇性:讓 JaCoCo 彙總報告產生成為「檢查」生命週期階段的一部分

報告彙總邏輯不會自動檢查所有子專案的涵蓋率資料以進行彙總。相反地,會選取 jacocoAggregation 設定的直接和傳遞式 專案相依性 以進行可能的彙總。

使用者還必須宣告一個或多個類型為 JacocoCoverageReport 的報告。每個報告執行個體都會指定 testType 屬性,用於比對產生涵蓋率資料的測試套件。會為每個使用者定義的報告合成一個 JacocoReport 工作,並執行彙總。呼叫此工作會導致在 jacocoAggregation 設定的相依專案中執行測試。

執行測試並產生報告

$ ./gradlew testCodeCoverageReport

BUILD SUCCESSFUL
25 actionable tasks: 25 executed

現在可以在 code-coverage-report/build/reports/jacoco/testCodeCoverageReport 下找到 XML 和 HTML 報告。

如需更多資訊,請參閱 Java 專案章節中的測試