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

使用JUnit5时找不到SpringExtension类的问题求助

问题分析与解决

核心原因:缺少Spring Boot测试起步依赖

你遇到的cannot find symbol: class SpringExtension错误,本质是项目未引入spring-boot-starter-test依赖——该包包含SpringExtension类,以及Spring Boot集成JUnit5所需的所有核心测试组件。

解决方案步骤

1. 添加测试起步依赖

在pom.xml的<dependencies>块中加入以下依赖,同时移除重复的JUnit Jupiter相关依赖(因为starter-test已经包含这些组件):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <!-- 无需手动指定版本,parent已统一管理所有Spring Boot组件版本 -->
</dependency>

2. 简化测试类注解(推荐)

从Spring Boot 2.2版本开始,@SpringBootTest注解已经自动集成了@ExtendWith(SpringExtension.class)的功能,完全可以去掉手动添加的@ExtendWith注解,简化代码为:

@SpringBootTest
public class YourTestClass {
    // 测试逻辑代码
}

3. 修复pom版本不一致问题(重要)

你的pom存在版本冲突风险:

  • parent指定Spring Boot 3.3.0,但spring-boot-starter-web、spring-boot-starter-jooq等依赖手动指定了3.2.6版本
  • 同时引入了不同版本的Spring核心组件(如spring-orm 6.1.8和spring-context 6.0.13)

建议移除所有Spring相关依赖的手动版本号,依赖parent的版本管理统一版本,避免兼容性问题。例如:

<!-- 修正后的web依赖,移除手动指定的version -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

修正后的关键依赖片段示例

<dependencies>
    <!-- 移除多余的spring-boot-dependencies导入,parent已包含该配置 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jooq</artifactId>
    </dependency>
    <!-- 移除手动指定版本的spring-orm、spring-context、spring-jdbc,starter会自动引入对应兼容版本 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope> <!-- 建议添加runtime scope,仅运行时生效 -->
    </dependency>
    <!-- jOOQ相关依赖保留,若需版本统一可通过parent的dependencyManagement配置 -->
    <dependency>
        <groupId>org.jooq</groupId>
        <artifactId>jooq</artifactId>
        <version>3.19.9</version>
    </dependency>
    <!-- 测试依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:49:50