使用 Maven 生成 JaCoCo 代码覆盖率报告

Nic*_*ryc 5 code-coverage maven jacoco

我不明白,我尝试用 JaCoCo 和 Maven 生成代码覆盖率报告,最简单的。

我的 pom.xml 中有以下插件:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>${jacoco.version}</version>
    <executions>
      <execution>
        <id>prepare-agent</id>
        <goals>
          <goal>prepare-agent</goal>
        </goals>
      </execution>
      <execution>
        <id>report</id>
        <phase>prepare-package</phase>
        <goals>
          <goal>report</goal>
        </goals>
      </execution>
      <execution>
        <id>post-unit-test</id>
        <phase>test</phase>
        <goals>
          <goal>report</goal>
        </goals>
        <configuration>
          <!-- Sets the path to the file which contains the execution data. -->

          <dataFile>target/jacoco.exec</dataFile>
          <!-- Sets the output directory for the code coverage report. -->
          <outputDirectory>target/my-reports</outputDirectory>
        </configuration>
      </execution>
    </executions>
    <configuration>
      <systemPropertyVariables>
        <jacoco-agent.destfile>target/jacoco.exec</jacoco-agent.destfile>
      </systemPropertyVariables>
  </configuration>
</plugin>
Run Code Online (Sandbox Code Playgroud)

当我尝试进行 mvn 测试时,它什么也没做。甚至没有错误或其他什么。它说为我的测试构建成功,但 Maven 似乎没有看到 JaCoCo。如果我尝试执行 mvn jacoco:report 无论如何我都会收到一条消息:Skipping JaCoCo execution due to missing execution data file.

小智 6

以下配置应该足够了:

<build>
  <plugins>
    <plugin>
      <groupId>org.jacoco</groupId>
      <artifactId>jacoco-maven-plugin</artifactId>
      <version>${jacoco.version}</version>
      <executions>
        <execution>
          <id>prepare-agent</id>
          <goals>
            <goal>prepare-agent</goal>
          </goals>
        </execution>
        <execution>
          <id>report</id>
          <phase>test</phase>
          <goals>
            <goal>report</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>
Run Code Online (Sandbox Code Playgroud)

然后可以在以下位置找到报告:target/site/jacoco/

它在您的情况下不起作用的原因:

  • 插件配置在里面pluginManagement
  • 该插件位于profile

mvn test执行for时还要检查 Maven 日志jacoco-maven-plugin。欲了解更多信息,请运行mvn -X test