Spring Boot低版本升级高版本后JUnit测试类编译错误问题
Spring Boot 2.1.7.RELEASE 升级至 2.5.5 后 JUnit 静态导入编译错误解决方案
问题根因
- Spring Boot 从 2.2.RELEASE 版本开始,默认测试依赖从 JUnit 4 切换为 JUnit 5(Jupiter),原有 JUnit 4 的 API 包路径在默认依赖中不再内置
import static org.junit.Assert.assertEquals;属于 JUnit 4 的断言类导入语句,项目升级后无对应依赖包因此编译报错
解决方案
方案1:迁移代码适配 JUnit 5(推荐)
将原有 JUnit 4 的相关导入替换为 JUnit 5 对应的 API 即可:
- 原静态断言导入
import static org.junit.Assert.*;替换为import static org.junit.jupiter.api.Assertions.*; - 其他 JUnit 4 常用注解对应替换:
@org.junit.Test替换为@org.junit.jupiter.api.Test@org.junit.Before替换为@org.junit.jupiter.api.BeforeEach@org.junit.After替换为@org.junit.jupiter.api.AfterEach@org.junit.BeforeClass替换为@org.junit.jupiter.api.BeforeAll@org.junit.AfterClass替换为@org.junit.jupiter.api.AfterAll
方案2:保留 JUnit 4 依赖不修改原有代码
如果暂时不想迁移代码,可以手动在 pom.xml(Maven 项目)或者 build.gradle(Gradle 项目)中引入 JUnit 4 的依赖,确保原有 API 可用:
Maven 项目依赖配置示例:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency>
Gradle 项目依赖配置示例:
testImplementation 'junit:junit:4.13.2'
内容的提问来源于stack exchange,提问作者Ravindra Pandya
相关产品推荐
相关产品推荐

