如何在Maven test阶段生成Jacoco报告:instrumented类处理报错
问题根因
错误的核心是Jacoco离线插桩的执行顺序逻辑不匹配:
- 你将code-coverage profile设置为默认激活,执行
mvn test时会自动触发jacoco的instrument目标,将target/classes下的类插桩。但test阶段执行时,restore-instrumented-classes恢复原始类的步骤还未运行,生成报告时读取到的是插桩后的类,Jacoco生成报告必须依赖未插桩的原始类,因此触发报错。 - 你跑完整code-coverage profile流程时restore步骤正常执行,生成报告时读到的是恢复后的原始类,所以可以正常生成报告。
解决方案
步骤1:修改profile默认激活配置
将profile中的<activeByDefault>true</activeByDefault>改为false,避免每次跑test都自动触发离线插桩逻辑,只有专门生成覆盖率时才激活该profile。
步骤2:调整Jacoco插件执行阶段绑定
给Jacoco的三个执行节点明确绑定执行阶段,保证执行顺序正确,修改后的配置如下:
<executions> <!-- 测试编译后、跑测试前插桩 --> <execution> <id>default-instrument</id> <goals> <goal>instrument</goal> </goals> <phase>process-test-classes</phase> </execution> <!-- 测试跑完立即恢复原始类 --> <execution> <id>default-restore-instrumented-classes</id> <goals> <goal>restore-instrumented-classes</goal> </goals> <phase>test</phase> </execution> <!-- 用原始类生成报告 --> <execution> <id>default-report</id> <goals> <goal>report</goal> </goals> <phase>verify</phase> </execution> </executions>
步骤3:调整执行命令
- 日常仅跑单元测试不需要生成覆盖率时,直接执行
mvn test即可,不会触发插桩逻辑,不会报错 - 需要生成覆盖率报告时,指定激活code-coverage profile,执行
mvn clean verify -P code-coverage,会按顺序执行插桩、跑测试、恢复原始类、生成报告的全流程,不会再触发类已插桩的错误
步骤4(可选):升级Jacoco版本
你当前使用的0.8.2版本较旧,新版本修复了大量插桩、PowerMock适配相关的bug,可以将${jacocoVersion}升级到0.8.11及以上的稳定版本。
内容的提问来源于stack exchange,提问作者Nagesh
相关产品推荐
相关产品推荐

