升级至最新maven-surefire-plugin与JUnit5后出现NoClassDefFoundError
JUnit 5.10.3 + Maven Surefire 3.3.0 出现
SurefireBooterForkException 问题的解决办法 问题现象
- 组合使用JUnit 5.10.3和maven-surefire-plugin 3.3.0时,抛出
SurefireBooterForkException,根因是NoClassDefFoundError: org.apache.maven.surefire.report.RunModeSetter - 回退到maven-surefire-plugin 3.0.0-M3后问题消失
- 环境:Apache Maven 3.9.0、Java 1.8.0_412、Windows 10,已使用JUnit 5 BOM,尝试过engine+api、仅api等依赖组合
已知原因
这是maven-surefire-plugin在Java 8环境下的兼容性问题。从3.0.0-M4版本开始,Surefire插件调整了内部类的加载逻辑,部分类(比如RunModeSetter)的加载机制在Java 8下存在缺陷,导致找不到类的错误,但在Java 11及以上版本中可正常运行。
解决办法
1. 配置Surefire插件兼容Java 8
在pom.xml的surefire插件配置中添加以下参数,强制插件使用兼容Java 8的类加载模式:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.3.0</version> <configuration> <forkCount>1</forkCount> <reuseForks>false</reuseForks> <useSystemClassLoader>true</useSystemClassLoader> <useManifestOnlyJar>false</useManifestOnlyJar> <argLine>-Djava.version=1.8</argLine> </configuration> </plugin>
2. 升级Java版本(若项目允许)
如果项目没有强依赖Java 8,升级到Java 11或更高版本,Surefire 3.3.0对高版本Java的兼容性更完善,可直接避免此类问题。
3. 使用兼容Java 8的Surefire版本
若上述配置无效,可继续使用3.0.0-M3版本,或选择3.0.0-M7之前的版本(如3.0.0-M6),这些版本在Java 8环境下的兼容性更稳定。
4. 确保JUnit 5依赖完整
使用JUnit 5 BOM时,必须正确引入junit-jupiter-engine(运行测试的核心依赖),完整依赖配置示例:
<dependencyManagement> <dependencies> <dependency> <groupId>org.junit</groupId> <artifactId>junit-bom</artifactId> <version>5.10.3</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <scope>test</scope> </dependency> </dependencies>
内容的提问来源于stack exchange,提问作者mnlaptev
相关产品推荐
相关产品推荐

