You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

2.3.3.RELEASE版spring-boot-starter-test引入后测试用例不执行问题

核心原因

Spring Boot 从2.2.x版本开始,spring-boot-starter-test默认移除了JUnit4兼容引擎junit-vintage-engine的内置依赖,仅默认集成JUnit Jupiter(JUnit 5)的测试引擎。

你遇到的问题根因如下:

  • 项目中现存的测试用例是基于JUnit4语法编写的(使用org.junit.Test、org.junit.runner.RunWith等JUnit4包下的注解),没有junit-vintage-engine时,Maven Surefire/Failsafe测试插件无法识别这类JUnit4测试用例,因此构建阶段不会执行
  • 显式引入junit-vintage-engine后,相当于额外补充了JUnit4的执行引擎,插件就可以正常识别并执行JUnit4版本的测试用例

可选修正方案

方案1:继续沿用JUnit4测试语法

不需要修改现有测试代码,只需要在引入spring-boot-starter-test时显式补充junit-vintage-engine依赖即可,坐标参考:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <!-- 全局继承了spring-boot-starter-parent时不需要写version -->
    <version>2.3.3.RELEASE</version>
</dependency>
<!-- 额外补充JUnit4兼容引擎 -->
<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <scope>test</scope>
</dependency>

方案2:迁移现有测试到JUnit5语法

不需要额外引入junit-vintage-engine,把原有测试代码的JUnit4注解替换为JUnit5对应注解即可:

  • 把import org.junit.Test替换为import org.junit.jupiter.api.Test
  • 把import org.junit.runner.RunWith替换为import org.junit.jupiter.api.extension.ExtendWith,对应Spring测试的注解改为@ExtendWith(SpringExtension.class),或者直接使用Spring Boot 2.2+提供的@SpringBootTest注解(默认已经集成了Spring扩展)
  • 其他JUnit4的断言、规则等对应替换为JUnit5的API即可

内容的提问来源于stack exchange,提问作者kama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:30:04