当你在 JUnit 测试类上使用 @RunWith(SpringRunner.class)
但出现找不到 SpringRunner
的错误时,这通常意味着缺少必要的依赖或者 JUnit 版本不匹配。
SpringRunner
是 Spring Boot 和 Spring TestContext 框架为 JUnit 提供的一个测试运行器,它允许你利用 Spring 的特性来运行测试。从 JUnit 5 开始,测试运行器的使用方式略有变化。
解决方案
-
检查依赖:
- 确保你的项目中包含了
spring-boot-starter-test
或者对应的 Spring 测试支持依赖。 - 如果你使用的是 Maven,请确保有以下依赖(以 Spring Boot 为例):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
- 对于 Gradle,应该添加类似这样的依赖:
testImplementation('org.springframework.boot:spring-boot-starter-test') { exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' }
- 确保你的项目中包含了
-
JUnit 版本问题:
- 如果你的项目使用的是 JUnit 4,那么
@RunWith(SpringRunner.class)
应该正常工作。 - 如果你的项目已经迁移到 JUnit 5,则需要更新你的测试代码,因为 JUnit 5 不再使用
@RunWith
注解,而是使用@ExtendWith
注解。- 使用
@ExtendWith(SpringExtension.class)
替换@RunWith(SpringRunner.class)
:@ExtendWith(SpringExtension.class) public class YourTestClass { // ... }
- 使用
- 如果你的项目使用的是 JUnit 4,那么
-
清理和重建项目:
- 运行
mvn clean install
(Maven) 或gradlew clean build
(Gradle) 来确保所有依赖都被正确下载并构建。
- 运行