Maven环境下Jacoco未统计Cucumber测试代码覆盖率问题求助
嘿,我之前也碰到过类似的坑,结合你给出的pom.xml配置,梳理几个关键的排查点,应该能解决覆盖率显示0%的问题:
1. 先修复Jacoco插件里的明显配置错误
你Jacoco配置里有个语法问题,<excludes>标签里居然嵌套了<include>,这肯定会导致配置失效:
<excludes><include>**/libs/*</include></excludes>
如果是想排除libs目录下的类,应该改成:
<excludes> <exclude>**/libs/*</exclude> </excludes>
另外你配置了两个report执行节点(id="report"和id="post-unit-test"),这容易导致报告生成时机混乱,建议保留一个就行,比如统一在test阶段执行报告生成。
2. 确保Jacoco Agent注入到Cucumber测试进程
Jacoco的prepare-agent目标会生成jacoco.agent.argLine参数,但得让Surefire插件用这个参数启动测试才行。你当前的Surefire配置没引用这个参数,必须加上:
<argLine>${jacoco.agent.argLine}</argLine>
要是你还有其他JVM参数,比如内存配置,直接合并到这里就行:
<argLine>${jacoco.agent.argLine} -Xmx512m</argLine>
3. 升级并简化Surefire插件配置
你用的Surefire 2.19.1版本太老了,和Cucumber 5.x、JUnit 5兼容性可能有问题。建议升级到最新稳定版(比如3.2.5),而且新版本已经内置了JUnit 4/5的支持,不需要手动加junit-jupiter-engine和surefire-junit47依赖。调整后的配置可以这样:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.2.5</version> <configuration> <testFailureIgnore>true</testFailureIgnore> <argLine>${jacoco.agent.argLine}</argLine> <!-- 指定Cucumber测试运行器的类,确保Surefire能找到并执行它们 --> <includes> <include>**/*Runner.class</include> </includes> </configuration> </plugin>
4. 修正Cucumber依赖的Scope
你的cucumber-java和cucumber-core没加<scope>test</scope>,这会导致它们被打包到生产代码里,还可能影响测试类加载。赶紧加上test scope:
<dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-java</artifactId> <version>5.5.0</version> <scope>test</scope> </dependency> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-core</artifactId> <version>5.5.0</version> <scope>test</scope> </dependency>
另外cucumber-jvm-deps在Cucumber 5.x里已经被废弃了,直接删掉这个依赖就行,cucumber-core已经包含了所需的依赖。
5. 验证Jacoco数据文件是否正常生成
执行mvn clean test后,去看看target/jacoco.exec文件有没有生成,而且大小不能是0。如果文件为空,那肯定是前面的argLine配置没生效,Jacoco Agent没抓到测试执行数据。
最后改完配置,执行mvn clean test jacoco:report生成最新报告,应该就能看到Cucumber测试的覆盖率数据了。
内容的提问来源于stack exchange,提问作者Saroj Nandi

