Maven Jacoco覆盖率报告问题:忽略失败单元测试仍无法生成
问题描述
我正在评估一款AI生成的单元测试工具,用Maven跟踪代码覆盖率和测试运行情况。但只要有单元测试失败,就生成不了覆盖率报告。我试过执行以下命令:
mvn clean verify -Dmaven.test.failure.ignore=truemvn -Dmaven.test.skip=true surefire-report:report
但都没用。我不想手动修复或删除失败的测试,免得影响评估结果。
以下是项目的pom.xml内容:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.dailycodebuffer</groupId> <artifactId>JaCoCo-Demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>JaCoCo-Demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.5</version> <executions> <execution> <goals> </goals> </execution> <execution> <id>report</id> <phase>prepare-package</phase> <goals> </goals> </execution> </executions> </plugin> </plugins> </build> <profiles> <profile> <id>run-tests</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> </configuration> </plugin> </plugins> </build> </profile> </profiles> </project>
解决方案
修复JaCoCo插件配置
当前pom中的JaCoCo插件缺少关键的prepare-agent目标绑定,这是收集覆盖率数据的前提。修改插件配置如下:<plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.5</version> <executions> <execution> <id>jacoco-prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>jacoco-report</id> <phase>verify</phase> <goals> <goal>report</goal> </goals> </execution> </executions> </plugin>prepare-agent会在测试启动前配置JVM参数,用于收集代码执行数据- 将
report目标绑定到verify阶段,确保测试完成后生成覆盖率报告
正确执行命令
执行以下命令,忽略测试失败同时触发覆盖率报告生成:mvn clean verify -Dmaven.test.failure.ignore=true注意:不要使用
-Dmaven.test.skip=true,该参数会跳过所有测试,导致JaCoCo无法收集任何覆盖率数据。查看报告
执行完成后,覆盖率报告会生成在target/site/jacoco/index.html路径下,直接用浏览器打开即可查看。
内容的提问来源于stack exchange,提问作者maddox.123
相关产品推荐
相关产品推荐

