如何在Maven中使用JUnit 5与Java 10?解决插件冲突问题
我之前在Java 10项目里整合JUnit 5时也踩过一模一样的坑!当时折腾了好一阵才把Maven的插件配置调对,正好给你分享下完整的解决方案:
问题根源梳理
Java 10带来了模块化等新特性,旧版的maven-compiler-plugin依赖的ASM库版本太低,没法识别Java 10的字节码,所以必须替换成org.ow2.asm提供的兼容版本;另外JUnit 5的测试运行需要maven-surefire-plugin配合JUnit平台的提供者,不然测试根本跑不起来。
完整的Maven配置方案
我把关键的插件和依赖配置整理好了,你可以直接复制到你的pom.xml里:
1. Maven编译器插件(maven-compiler-plugin)
这个插件的核心是替换ASM依赖,同时指定正确的Java版本:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <!-- 推荐用这个版本,对Java10支持更稳定 --> <configuration> <release>10</release> <!-- 用release参数替代source/target,确保字节码完全符合Java10规范 --> </configuration> <dependencies> <!-- 替换默认ASM为支持Java10的版本 --> <dependency> <groupId>org.ow2.asm</groupId> <artifactId>asm</artifactId> <version>7.0</version> </dependency> <dependency> <groupId>org.ow2.asm</groupId> <artifactId>asm-commons</artifactId> <version>7.0</version> </dependency> <dependency> <groupId>org.ow2.asm</groupId> <artifactId>asm-tree</artifactId> <version>7.0</version> </dependency> </dependencies> </plugin>
2. Maven测试插件(maven-surefire-plugin)
要让JUnit 5的测试正常运行,必须引入JUnit平台的提供者依赖:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.2</version> <!-- 这个版本和JUnit5的兼容性最好 --> <dependencies> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-surefire-provider</artifactId> <version>1.5.2</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.5.2</version> </dependency> </dependencies> </plugin>
3. JUnit 5核心依赖
别忘了在<dependencies>块里加上JUnit 5的API和参数化测试依赖:
<dependencies> <!-- JUnit 5核心API --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.5.2</version> <scope>test</scope> </dependency> <!-- 参数化测试支持 --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-params</artifactId> <version>5.5.2</version> <scope>test</scope> </dependency> </dependencies>
几个关键注意点
- 确保你的Maven版本至少是3.5.4,旧版Maven对Java 10的支持很差,会出现各种奇怪的报错
- 所有JUnit相关的版本要保持一致(比如这里的5.5.2和1.5.2是配套的),版本不匹配会导致测试无法发现或运行
- 用
release参数替代source和target是Java 9+推荐的做法,能避免编译出不符合版本规范的字节码
这样配置之后,你应该就能正常在Java 10环境下用Maven编译和运行JUnit 5的测试了!
内容的提问来源于stack exchange,提问作者Ukonn Ra
相关产品推荐
相关产品推荐

