返回

如何使用 Jacoco 过滤非业务类,获得更具针对性的覆盖率报告?

见解分享

在进行接口测试代码覆盖率(Jacoco)方案的实施过程中,难免会遇到一些问题,比如测试报告中包含了大量非业务类的信息,导致报告杂乱无章,难以针对性地进行分析。这些非业务类通常包括配置、bean 和适配器类,其中大部分都没有业务代码,统计出来的覆盖率也会受到影响。

为了解决这个问题,我们可以使用 Jacoco 提供的过滤功能,将这些非业务类排除在测试报告之外。通过这种方式,我们可以获得更具针对性的覆盖率报告,帮助我们快速识别需要改进的代码部分。

在 Maven 中,可以通过在 pom.xml 文件中添加以下配置来实现过滤:

<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.7</version>
  <executions>
    <execution>
      <id>prepare-agent</id>
      <goals>
        <goal>prepare-agent</goal>
      </goals>
      <configuration>
        <propertyName>jacocoArgLine</propertyName>
        <includes>
          <include>com.example.project.*</include>
        </includes>
        <excludes>
          <exclude>com.example.project.config.*</exclude>
          <exclude>com.example.project.bean.*</exclude>
          <exclude>com.example.project.adapter.*</exclude>
        </excludes>
      </configuration>
    </execution>
    <execution>
      <id>report</id>
      <phase>test</phase>
      <goals>
        <goal>report</goal>
      </goals>
      <configuration>
        <dataFile>${project.build.directory}/jacoco.exec</dataFile>
        <outputDirectory>${project.build.directory}/jacoco-report</outputDirectory>
      </configuration>
    </execution>
  </executions>
</plugin>

在 Gradle 中,可以通过在 build.gradle 文件中添加以下配置来实现过滤:

jacoco {
  toolVersion = "0.8.7"
  reportsDir = file("$buildDir/jacoco")
  finalizedBy 'jacocoTestReport'

  include "com.example.project.*"
  exclude "com.example.project.config.*"
  exclude "com.example.project.bean.*"
  exclude "com.example.project.adapter.*"
}

通过上述配置,我们就可以将非业务类从测试报告中排除出去,从而获得更具针对性的覆盖率报告。

除了使用 Jacoco 的过滤功能之外,我们还可以通过其他方式来减少测试报告中的非业务类信息。例如,我们可以使用 Maven 的 maven-surefire-plugin 插件来排除不需要测试的类或包。这样,就可以避免在测试报告中生成这些类的覆盖率信息。

通过使用 Jacoco 的过滤功能和其他优化手段,我们可以获得更具针对性的覆盖率报告,帮助我们快速识别需要改进的代码部分,从而提高代码质量。