理解JaCoCo与Maven集成 | AI生成和翻译

Home 2025.09

明白了——以下是您当前POM文件中JaCoCo各组件协同工作的步骤及原理说明。


该POM文件创建的两类覆盖率数据流

  1. 单元测试覆盖率(Surefire路径)
  1. 集成测试覆盖率(Jetty路径)

生命周期流程(执行mvn verify时的过程)

  1. compile

    • Spotless格式化(spotless-maven-plugin)和Checkstyle检查(maven-checkstyle-plugin)。
    • 准备WAR包(maven-war-plugin)。
  2. test (Surefire)

    • 如有单元测试,它们会在prepare-agent注入的argLine参数下运行 → 覆盖率数据写入target/jacoco.exec
  3. pre-integration-test

    • Jetty以守护模式启动:

      <daemon>true</daemon>
      

      Maven立即恢复控制权;Jetty持续运行并附带JaCoCo代理,将数据写入jacoco-it.exec

  4. integration-test

    • 您的Python测试访问运行中的应用程序:

      <plugin>
        <artifactId>exec-maven-plugin</artifactId>
        <execution>
          <id>python-integration-tests</id>
          <phase>integration-test</phase>
          <goals><goal>exec</goal></goals>
          <configuration>
            <executable>python3</executable>
            <workingDirectory>${project.parent.basedir}</workingDirectory>
            <arguments>
              <argument>-m</argument><argument>unittest</argument>
              <argument>discover</argument><argument>tests/</argument>
              <argument>-v</argument>
            </arguments>
          </configuration>
        </execution>
      </plugin>
      

      这些测试会调用Jetty,因此覆盖率通过Jetty JVM的代理累积到target/jacoco-it.exec

  5. post-integration-test

    • 干净地停止Jetty:

      <execution>
        <id>stop-jetty</id>
        <phase>post-integration-test</phase>
        <goals><goal>stop</goal></goals>
        ...
      </execution>
      
  6. verify

    • 您使用IT数据文件和自定义输出目录生成独立的IT报告

      <execution>
        <id>report-it</id>
        <phase>verify</phase>
        <goals><goal>report</goal></goals>
        <configuration>
          <dataFile>${jacoco.it.exec}</dataFile>
          <outputDirectory>${project.reporting.outputDirectory}/jacoco-it
          </outputDirectory>
        </configuration>
      </execution>
      
    • 结果:HTML报告生成于target/site/jacoco-it/index.html,仅汇总集成测试覆盖率(来自Jetty)。

注意:如需单元测试报告,可添加另一个指向默认target/jacoco.exec并输出至target/site/jacocojacoco:report执行配置——保持单元测试与集成测试报告分离。


关于.exec文件的“新建或替换?”问题

最佳实践(避免混合旧数据):


原始XML中各相关模块的功能说明(按引用关系)


实用技巧 / 小幅改进


总结


Back

openai/gpt-5

Donate