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

高版本spring-boot-starter-parent执行mvn test无法运行测试用例

问题原因
  • Spring Boot 从2.4.0版本开始调整了spring-boot-starter-parent的默认测试依赖配置:2.3.x及更早版本默认同时集成JUnit 4、JUnit 5(Jupiter)两套测试引擎,配套的Maven Surefire插件可同时识别两种规范的测试用例;2.4.0及更高版本(包含使用的2.7.0版本)默认移除了JUnit Vintage(JUnit 4兼容引擎)依赖,仅保留JUnit 5作为默认测试引擎。
  • 现有测试类使用了@RunWith(SpringRunner.class)注解,这是JUnit 4规范的专属注解,对应的测试用例属于JUnit 4体系。在缺少JUnit Vintage兼容引擎的环境下,Maven执行测试扫描时无法识别这类用例,就会出现无测试用例运行的现象。
  • 现有测试类命名DemoServiceTest、DemoControllerTest符合Maven Surefire插件的默认扫描规则,不存在命名不规范导致扫描不到的问题。
解决方案

可根据实际需求二选一:

方案1:迁移测试代码到JUnit 5规范(官方推荐)

不需要额外添加依赖,直接修改测试类写法即可:

  • 删除@RunWith(SpringRunner.class)注解,Spring Boot 2.7版本自带的测试注解(@SpringBootTest、@WebMvcTest等)已经内置了JUnit 5对应的扩展注解,不需要手动指定运行器
  • 测试方法上的@Test注解替换为org.junit.jupiter.api.Test,不要引用旧的org.junit.Test包下的同名注解

修改后的测试类示例:

@SpringBootTest
public class DemoServiceTest {

    @org.junit.jupiter.api.Test
    void testServiceMethod() {
        // 测试逻辑
    }
}
@WebMvcTest
public class DemoControllerTest {

    @org.junit.jupiter.api.Test
    void testControllerMethod() {
        // 测试逻辑
    }
}

方案2:保留JUnit 4写法,补全兼容依赖

如果不想修改现有测试代码,直接在pom.xml的dependencies节点下添加JUnit Vintage兼容引擎依赖即可:

<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <scope>test</scope>
</dependency>

添加依赖后刷新Maven配置,重新执行mvn test即可正常识别运行所有JUnit 4写法的测试用例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 04:39:19