多模块Gradle项目Jacoco报告含测试类问题及修复咨询
Hey, I see the issue here—your current Jacoco configuration isn't filtering out compiled test classes, which is why your coverage report is including test package code and skewing the results. We only want to measure coverage for your main source code, right?
Here's the corrected Gradle configuration for your multi-module project:
subprojects { subproject -> jacocoTestReport { additionalSourceDirs = files(sourceSets.main.allSource.srcDirs) // 🔑 Critical fix: Filter class directories to only include main source code classDirectories.setFrom( files(sourceSets.main.output).filter { file -> file.path.startsWith(sourceSets.main.java.outputDir.path) } ) sourceDirectories = files(sourceSets.main.allSource.srcDirs) reports { html.enabled = true xml.enabled = true csv.enabled = false } } test { useTestNG() } test.finalizedBy(project.tasks.jacocoTestReport) }
What's changed?
The key adjustment is the classDirectories configuration:
- We explicitly target only the compiled classes from your
mainsource set usingsourceSets.main.output. - The
filterensures we only include files from the main code's output directory, excluding any test code compilation artifacts that might have been included by default.
If you want even more precision (e.g., targeting specific packages in your main code), you can use path matching instead:
classDirectories.setFrom( sourceSets.main.output.asFileTree.matching { include 'com/yourcompany/**' // Replace with your main package path exclude 'test/**' // Explicitly exclude test-related classes just to be safe } )
After applying this change, your Jacoco report will only show coverage for code in the main package, giving you accurate, meaningful coverage metrics.
内容的提问来源于stack exchange,提问作者Ermintar

