Android项目中SonarQube无法统计Kotlin文件代码覆盖率问题排查
问题修复方案
当前Kotlin覆盖率数据缺失的核心原因是Jacoco报告生成配置仅覆盖了Java相关的源码与编译产物路径,未包含Kotlin对应的路径,导致Kotlin的覆盖数据没有被写入最终的Jacoco XML报告,SonarQube自然无法读取到相关统计。
需修改的两处配置:
1. 修复SonarQube配置的语法问题
你当前的sonarqube配置里第二行property少了右括号,修正后为:
sonarqube { properties{ property "sonar.junit.reportPaths", "build/test-results/testDebugUnitTest/*.xml" property("sonar.coverage.jacoco.xmlReportPaths", "build/reports/jacocoTestReport.xml") } }
2. 修改Jacoco.gradle里的jacocoTestReport任务配置
需要同时引入Kotlin的源码路径和Kotlin编译后的类文件路径,同时修正原配置里源码路径多余的根路径斜杠,修改后的任务代码如下:
task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest']) { group = "Reporting" description = "Generate Jacoco coverage reports for Debug build" reports { xml.enabled(true) html.enabled(true) xml.destination(file("build/reports/jacocoTestReport.xml")) } // 同时包含Java和Kotlin的编译产物目录 def javaDebugTree = fileTree(dir: "${buildDir}/intermediates/javac/debug/classes", excludes: coverageExclusions) def kotlinDebugTree = fileTree(dir: "${buildDir}/tmp/kotlin-classes/debug", excludes: coverageExclusions) // 同时包含Java和Kotlin的源码目录 def mainSrc = ["src/main/java", "src/main/kotlin"] additionalSourceDirs.from = files(mainSrc) sourceDirectories.from = files(mainSrc) classDirectories.from = files([javaDebugTree, kotlinDebugTree]) executionData.from = fileTree(dir: project.buildDir, includes: [ 'jacoco/testDebugUnitTest.exec', 'outputs/code-coverage/connected/*coverage.ec' ]) }
修改配置后重新执行单元测试、Jacoco报告生成任务,再将结果推送到SonarQube即可正常统计Kotlin文件的覆盖率,你正在使用的Jacoco 0.8.6版本本身支持Kotlin覆盖率统计,无需额外升级版本。
内容的提问来源于stack exchange,提问作者Wale
相关产品推荐
相关产品推荐

