升级JUnit Jupiter Engine至5.10.0后Spring Boot3应用测试发现失败
问题根源
你遇到的TestEngine with ID 'junit-jupiter' failed to discover tests错误,核心原因是JUnit Jupiter组件版本不兼容:
Spring Boot 3.1.2的父pom默认管理JUnit Jupiter所有组件(如junit-jupiter-api、junit-jupiter-engine)的版本为5.9.3,但你仅手动升级了junit-jupiter-engine到5.10.0,导致engine依赖的API类(如org.junit.jupiter.api.io.TempDirFactory)在旧版本的junit-jupiter-api中不存在,触发类找不到异常。
解决方案
方案1:使用Spring Boot管理的JUnit版本
直接移除junit-jupiter-engine依赖中手动指定的版本号,让Spring Boot父pom统一管理所有JUnit组件版本(5.9.3),确保版本一致:
<dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <scope>test</scope> <!-- 移除手动指定的version,使用Spring Boot parent管理的版本 --> </dependency>
方案2:统一升级所有JUnit Jupiter组件到5.10.0
如果必须使用5.10.0版本,通过导入JUnit Jupiter的BOM来统一所有相关组件的版本,避免单独升级某一个组件导致的冲突:
在pom.xml的dependencyManagement中添加:
<dependencyManagement> <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-bom</artifactId> <version>5.10.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
之后你的junit-jupiter-engine依赖无需指定版本,会自动使用BOM中的5.10.0版本,且所有JUnit Jupiter相关组件版本保持一致。
额外检查:确保Surefire插件版本兼容
当前使用的maven-surefire-plugin:3.0.0支持JUnit 5.10.0,若仍有问题可升级到最新稳定版(如3.2.2):
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.2.2</version> </plugin> </plugins> </build>
内容的提问来源于stack exchange,提问作者João Pedro Schmitt

