junit 5 运行报错因ide误用junit 4模式:需删@ runwith、改用@extendwith;pom.xml引入junit-jupiter≥5.7.0;surefire插件≥2.22.2并配置junit platform;避免混用junit 4/5注解;ide中确认测试scope和框架识别正确。

JUnit 5 运行时找不到 @RunWith 或报错 Class not found: "org.junit.runner.JUnitCore"
这是典型的 IDE(如 IntelliJ 或 Eclipse)把 JUnit 4 的启动方式套在 JUnit 5 测试类上导致的。JUnit 5 完全废弃了 @RunWith,改用 @ExtendWith 和原生引擎发现机制,但 IDE 默认可能仍按旧模式扫描。
实操建议:
- 检查测试类是否混用了
@RunWith(SpringRunner.class)或@RunWith(JUnit4.class)—— JUnit 5 下必须删掉或替换为@ExtendWith(SpringExtension.class) - 确保
pom.xml中引入的是junit-jupiter(不是junit-vintage-engine),且版本 ≥ 5.7.0(避免早期兼容 bug) - IntelliJ:右键测试类 → Run 'XxxTest' → 看控制台顶部是否显示 “Using JUnit5”;若显示 “JUnit4”,说明 IDE 缓存了旧配置,需 File → Invalidate Caches and Restart
- Eclipse:项目右键 → Properties → Java Build Path → Libraries,确认没同时存在
junit-4.x.jar和junit-jupiter-api-5.x.jar,冲突时优先保留后者
IDE 能运行单个测试方法,但 mvn test 报 No tests were executed
根本原因常是 Maven Surefire 插件默认只识别 *Test.java 或 Test*.java 命名,而 JUnit 5 的引擎还需显式启用 —— IDE 不依赖这个规则,但命令行依赖。
实操建议:
- 在
pom.xml的<plugin><groupid>org.apache.maven.plugins</groupid><artifactid>maven-surefire-plugin</artifactid></plugin>下添加:<configuration> <includes> <include>**/*Test.java</include> </includes> <excludes> <exclude>**/integration/**</exclude> </excludes> </configuration> - 必须声明 Surefire 版本 ≥ 2.22.2,并显式引入 JUnit Platform:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M9</version> <dependencies> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-surefire-provider</artifactId> <version>1.3.2</version> </dependency> </dependencies> </plugin> - 确认测试类不在
src/main/java下,且包路径未被maven-compiler-plugin的testExcludes意外排除
混合使用 JUnit 4 和 JUnit 5 时,@BeforeClass 不执行或报 Method must be static
JUnit 4 的 @BeforeClass 要求方法 static,而 JUnit 5 的 @BeforeAll 默认不要求(除非在非静态内部类中)。混用时,IDE 可能误判注解归属,或 vintage 引擎加载失败。
实操建议:
- 彻底避免在同一个模块里混用两种生命周期注解;如需迁移,统一改为 JUnit 5 风格:
@BeforeAll/@AfterAll(非静态)、@BeforeEach/@AfterEach - 若必须保留部分 JUnit 4 测试(如遗留集成测试),则单独建
src/test/junit4目录,并配独立 Surefire execution,避免扫描干扰 - 检查是否意外引入了
junit-vintage-engine—— 它会让 JUnit 5 运行器尝试解析 JUnit 4 注解,但不保证语义一致,容易触发静态校验失败
IntelliJ 中右键 Run 单测,提示 Cannot resolve symbol 'Test' 但编译通过
这不是代码问题,而是 IDE 的测试框架识别配置没对齐源码语言级别或依赖 scope。常见于使用了 test scope 的 JUnit 5 依赖,但 IDE 没刷新或误判为 production classpath。
实操建议:
- 打开 File → Project Structure → Modules → Dependencies,找到
junit-jupiter-api,确认其Scope是Test,且勾选了Export(否则测试类无法感知 API) - 检查项目 SDK 和 Language Level 是否 ≥ 8(JUnit 5 最低要求 Java 8,但某些 IDE 对 8 和 11 的注解处理逻辑不同)
- 删掉
.idea/misc.xml中疑似残留的<option name="TEST_FRAMEWORK" value="JUnit4"></option>手动配置项,重启后让 IDE 自动探测 - 如果用了 Lombok,确认
lombok.config里没禁用lombok.addLombokGeneratedAnnotation = true—— 否则@Test可能被误判为未生成
最麻烦的其实是依赖传递:比如某个 spring-boot-starter-test 间接拉了 vintage engine,又没显式 exclude,结果 IDE 在后台偷偷启了双引擎,行为就不可预测。遇到诡异现象,先 mvn dependency:tree -Dincludes=junit 看实际加载了哪些 JUnit 相关 jar。










