如何通过Jacoco仅统计公共方法的覆盖率?
Absolutely! JaCoCo does support filtering coverage based on method access modifiers, so you can absolutely configure it to only track public methods when using the jacoco-maven-plugin. Here's how to set it up:
Using Direct Method-Level Filtering
The most straightforward approach is to use the methodIncludes configuration option in the plugin's report goal. This lets you explicitly define which methods to include in coverage calculations. For public methods, a simple pattern works perfectly:
<build> <plugins> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.11</version> <!-- Use the latest stable version --> <executions> <execution> <id>prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>generate-coverage-report</id> <phase>test</phase> <goals> <goal>report</goal> </goals> <configuration> <!-- Explicitly include only public methods --> <methodIncludes> <include>public *</include> </methodIncludes> </configuration> </execution> </executions> </plugin> </plugins> </build>
Alternative: Exclude Non-Public Methods
If you prefer a "blacklist" approach, you can exclude non-public methods using regex patterns in the excludes option. This is handy if you need more granular control over what gets excluded:
<configuration> <excludes> <!-- Filter out methods with private, protected, or package-private access --> <exclude>**/*.*(private|protected|package-private)*</exclude> </excludes> </configuration>
Key Notes
- Ensure you're using JaCoCo version 0.7.2 or higher—this is when the
methodIncludesfeature was introduced. - You can combine class-level
includes/excludeswith method-level filters if you want to restrict coverage to specific classes and their public methods. - After running
mvn test jacoco:report, the generated HTML/XML report will only display coverage statistics for your public methods, ignoring all non-public ones entirely.
内容的提问来源于stack exchange,提问作者Matias Fornara

