如何配置Intellij测试覆盖率功能使其适配Lombok
解决方案
方案1:配置IntelliJ自带覆盖率运行器忽略@Generated标注方法
该方案成本最低,适用于IntelliJ IDEA 2021.2及以上版本,操作步骤如下:
- 打开IDEA的
Settings/Preferences面板 - 依次进入
Build, Execution, Deployment > Coverage设置页 - 找到
Exclude methods annotated with配置项,点击添加按钮 - 填入你Lombok生成方法上标注的
@Generated注解的全类名,根据你的lombok.config配置选择即可,常见有三类:lombok.Generated(Lombok自带的生成注解,推荐优先使用)javax.annotation.Generatedjakarta.annotation.Generated
- 保存配置后重新用IDEA自带覆盖率运行器执行测试,Lombok生成的方法就会自动排除在覆盖率统计之外。
如果你的IDEA版本低于2021.2,不支持上述配置,可以使用下面的方案2。
方案2:配置JaCoCo支持IntelliJ内直接运行测试,兼容PowerMock
核心逻辑是用JaCoCo离线插桩替代默认的在线插桩,避免和PowerMock的字节码修改逻辑冲突,同时配置IDEA测试运行前自动执行插桩,无需手动执行全量mvn test。
第一步:调整pom.xml配置
<!-- JaCoCo插件配置 --> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.10</version> <!-- 建议使用最新稳定版,兼容更高版本JDK和IDEA --> <executions> <execution> <id>default-instrument</id> <goals> <goal>instrument</goal> </goals> </execution> <execution> <id>default-restore-instrumented-classes</id> <goals> <goal>restore-instrumented-classes</goal> </goals> </execution> </executions> </plugin> <!-- 可选:如果测试类路径不识别插桩后的类,添加build-helper插件配置插桩类路径优先级 --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.4.0</version> <executions> <execution> <id>add-instrumented-classes</id> <phase>process-test-classes</phase> <goals> <goal>add-classes</goal> </goals> <configuration> <sources> <source>${project.build.directory}/generated-classes/jacoco</source> </sources> </configuration> </execution> </executions> </plugin>
同时在dependencies中添加JaCoCo离线插桩依赖:
<dependency> <groupId>org.jacoco</groupId> <artifactId>org.jacoco.agent</artifactId> <classifier>runtime</classifier> <version>0.8.10</version> <!-- 和插件版本保持一致 --> <scope>test</scope> </dependency>
另外要确认你的lombok.config中已经开启了生成@Generated注解的配置:
lombok.addLombokGeneratedAnnotation = true
第二步:调整IDEA测试运行模板
- 打开
Run > Edit Configurations,点击Edit configuration templates,选择JUnit模板 - 找到
Before launch区域,删除默认的Build步骤 - 点击添加按钮,选择
Run Maven Goal,在命令行输入jacoco:instrument,点击确认 - 再添加一个
Build步骤,确保修改后的类被编译 - 保存模板配置,之后所有JUnit测试运行都会先执行JaCoCo插桩,无需手动执行全量maven测试
- 运行测试时选择JaCoCo作为覆盖率运行器,即可得到正确的覆盖率统计结果,且兼容PowerMock。
内容的提问来源于stack exchange,提问作者HibernateIndexIssues
相关产品推荐
相关产品推荐

