Skip to content

JaCoCo 代码覆盖率

JaCoCo(Java Code Coverage)是最流行的 Java 代码覆盖率工具,与 Gradle 完美集成。

基本配置

kotlin
plugins {
    java
    jacoco
}

jacoco {
    toolVersion = "0.8.11"
}

tasks.named<JacocoReport>("jacocoTestReport") {
    dependsOn(tasks.named("test"))
    
    reports {
        xml.required.set(true)    // SonarQube 需要
        html.required.set(true)   // 人工查看
        csv.required.set(false)
    }
    
    // 排除不需要统计的类
    classDirectories.setFrom(
        sourceSets.main.get().output.asFileTree.matching {
            exclude(
                "**/config/**",
                "**/dto/**",
                "**/*Application*",
                "**/*Exception*",
                "**/generated/**"
            )
        }
    )
}

// 覆盖率验证(不达标则构建失败)
tasks.named<JacocoCoverageVerification>("jacocoTestCoverageVerification") {
    violationRules {
        rule {
            limit {
                minimum = "0.80".toBigDecimal()   // 总体最低 80%
            }
        }
        
        rule {
            element = "CLASS"
            limit {
                counter = "LINE"
                value = "COVEREDRATIO"
                minimum = "0.60".toBigDecimal()    // 每个类最低 60%
            }
        }
    }
}

// 将覆盖率验证加入 check 任务
tasks.named("check") {
    dependsOn(tasks.named("jacocoTestReport"))
    dependsOn(tasks.named("jacocoTestCoverageVerification"))
}

运行命令

bash
# 运行测试并生成覆盖率报告
./gradlew test jacocoTestReport

# 查看 HTML 报告
# build/reports/jacoco/test/html/index.html

# 运行覆盖率验证
./gradlew jacocoTestCoverageVerification

多项目聚合覆盖率

kotlin
// 根项目 build.gradle.kts
plugins {
    `jacoco-report-aggregation`
}

dependencies {
    jacocoAggregation(project(":core"))
    jacocoAggregation(project(":web"))
    jacocoAggregation(project(":service"))
}

// 生成聚合报告
// ./gradlew testCodeCoverageReport

与 SonarQube 集成

kotlin
plugins {
    id("org.sonarqube") version "4.4.1.3373"
}

sonar {
    properties {
        property("sonar.projectKey", "my-project")
        property("sonar.host.url", "https://sonarqube.example.com")
        property("sonar.token", System.getenv("SONAR_TOKEN"))
        property("sonar.coverage.jacoco.xmlReportPaths", 
            "$buildDir/reports/jacoco/test/jacocoTestReport.xml")
    }
}

下一步