Maven编译通过但测试报UnsupportedClassVersionError预览特性未启用
解决Maven运行测试时预览特性未启用的问题
问题核心是仅配置了编译阶段的预览参数,但运行测试的Maven Surefire插件未将--enable-preview传递给JVM,导致执行测试类时JVM无法识别带预览特性的类文件。按以下步骤修复:
1. 确认maven-compiler-plugin配置正确
确保编译主代码和测试代码时都启用预览特性,同时指定匹配的Java版本:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.10.1</version> <!-- 需使用支持Java 17+的版本 --> <configuration> <source>17</source> <target>17</target> <testSource>17</testSource> <testTarget>17</testTarget> <compilerArgs> <arg>--enable-preview</arg> </compilerArgs> <testCompilerArgs> <arg>--enable-preview</arg> </testCompilerArgs> </configuration> </plugin>
2. 配置maven-surefire-plugin添加JVM参数
测试由Surefire插件启动JVM执行,必须在该插件中注入--enable-preview参数:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M7</version> <!-- 版本需适配Java 17+ --> <configuration> <argLine>--enable-preview</argLine> </configuration> </plugin>
3. 验证与调试
- 先通过命令行快速验证:执行
mvn clean test -DargLine="--enable-preview",如果运行成功,说明Surefire的配置是关键遗漏项。 - 检查项目全局properties,确保Java版本与编译插件配置一致:
<properties> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> <maven.compiler.release>17</maven.compiler.release> </properties> - 执行
mvn clean test,彻底清理旧编译文件后重新运行测试。
内容的提问来源于stack exchange,提问作者RandomB
相关产品推荐
相关产品推荐

