Cucumber 6.x迁移至7.x版本运行报错问题排查与咨询
Cucumber 6.x升级7.x后TestNG运行报NoClassDefFoundError问题排查方案
根本原因
报错java.lang.NoClassDefFoundError: io/cucumber/messages/internal/com/google/protobuf/GeneratedMessageV3属于典型的依赖版本不兼容问题,触发场景分为三类:
- Cucumber 6.x默认依赖19.x以下版本的
cucumber-messages,该版本内部protobuf类的打包路径和7.x强依赖的20.x+版本cucumber-messages完全不一致;如果升级时旧版本的cucumber-messages通过传递依赖残留在项目中,就会触发类找不到的报错。 - 升级时仅单独升级了
cucumber-java版本,没有同步升级cucumber-testng、cucumber-core等配套Cucumber组件,导致组件间版本校验不通过,拉取了错误版本的传递依赖。 - 项目中其他第三方依赖引入了3.19.4以下版本的
protobuf-java库,和Cucumber 7.x依赖的protobuf版本产生冲突,覆盖了正确版本的类文件。
可落地解决方案
方案1:通过BOM统一所有Cucumber组件版本
优先在pom.xml的dependencyManagement节点引入Cucumber官方BOM依赖,锁定所有Cucumber生态组件的版本,从根源避免版本不一致问题,参考配置如下:
<dependencyManagement> <dependencies> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-bom</artifactId> <version>7.14.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
引入具体Cucumber依赖时不需要再单独指定版本号,示例:
<dependencies> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-java</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-testng</artifactId> <scope>test</scope> </dependency> </dependencies>
注意:如果项目中用到cucumber-spring、cucumber-expressions等其他Cucumber生态组件,同样不需要指定版本,统一由cucumber-bom管理即可。
方案2:排查并排除冲突的低版本依赖
执行Maven依赖树命令,定位冲突的依赖来源:
mvn dependency:tree -Dincludes=io.cucumber:cucumber-messages,com.google.protobuf:protobuf-java
如果输出结果中存在版本低于20.0.0的cucumber-messages,或者版本低于3.19.4的protobuf-java,在引入该依赖的位置添加排除规则,示例:
<dependency> <groupId>com.example</groupId> <artifactId>third-party-test-lib</artifactId> <version>1.2.0</version> <exclusions> <exclusion> <groupId>io.cucumber</groupId> <artifactId>cucumber-messages</artifactId> </exclusion> <exclusion> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> </exclusion> </exclusions> </dependency>
方案3:清理损坏的本地依赖缓存
如果依赖配置确认无误仍报错,大概率是本地Maven仓库中的cucumber-messages包下载损坏,执行以下命令清理缓存后重新拉取依赖即可:
# 替换为本地maven仓库的实际路径 rm -rf ~/.m2/repository/io/cucumber/cucumber-messages/ mvn clean test -U
验证标准
完成上述操作后重新执行测试,确认TestNG可以正常实例化SequentialRunnerTest类,@AfterAll等Cucumber 7.x新增钩子可以正常触发即为修复完成。
内容的提问来源于stack exchange,提问作者Dhrumil Soni
相关产品推荐
相关产品推荐

