You need to enable JavaScript to run this app. 如何让Gradle Jacoco在控制台输出含行号的代码覆盖率详情?
优惠活动
大模型
产品
解决方案
定价
更多

如何让Gradle Jacoco在控制台输出含行号的代码覆盖率详情?

Gradle 控制台输出行级覆盖率方案

你可以通过以下两种常用方案实现类似Python Coverage.py的行级未覆盖内容控制台输出效果:

方案一:升级配置 org.barfuin.gradle.jacocolog 插件

你当前使用的1.2.4版本插件不支持行级信息输出,升级到2.0+版本后可直接配置输出未覆盖行号:

  • 替换插件声明版本:
plugins {
    // 保留原有其他插件
    id 'org.barfuin.gradle.jacocolog' version '3.1.0'
}
  • 新增插件配置块:
jacocoLog {
    // 显示每个类的未覆盖行号
    showMissedLines = true
    // 可配置覆盖率低于指定阈值时才输出详情,也可设为始终输出
    logThresholds {
        lineCoverage 0.0 // 设为0表示始终打印行级信息
    }
}
  • 执行测试时运行 ./gradlew test jacocoLogTest 即可在控制台看到每个文件的未覆盖具体行号。

方案二:自定义Gradle任务解析Jacoco报告

如果不想修改现有插件版本,可直接新增自定义任务解析Jacoco生成的XML报告,打印行级信息:

task printMissedLines(dependsOn: jacocoTestReport) {
    doLast {
        def parser = new XmlSlurper()
        def reportFile = file("${buildDir}/reports/jacoco/test/jacocoTestReport.xml")
        if (!reportFile.exists()) return
        def report = parser.parse(reportFile)
        report.package.each { pkg ->
            pkg.class.each { cls ->
                def className = cls.@name
                def missedLines = []
                cls.line.each { line ->
                    if (line.@mi.toInteger() > 0) {
                        missedLines.add(line.@nr)
                    }
                }
                if (!missedLines.isEmpty()) {
                    println "文件 ${className} 未覆盖行号:${missedLines.join(', ')}"
                }
            }
        }
    }
}
// 测试执行后自动运行该任务
test.finalizedBy printMissedLines

执行 ./gradlew test 后就会自动在控制台输出所有文件的未覆盖行号。

内容的提问来源于stack exchange,提问作者Edward Chamberlain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 21:45:08