Eclipse中运行JUnit测试提示MockitoJUnitRunner类不存在的解决方法问询
Eclipse环境JUnit无法找到Mockito相关类解决方案
错误本质
报错java.lang.ClassNotFoundException: MockitoJUnitRunner是运行时类路径未包含Mockito对应类文件导致,可按照以下步骤排查解决:
解决方案
- 确认依赖引入正确
若为Maven项目,检查pom.xml是否引入匹配的JUnit和Mockito依赖(JUnit4场景示例):
若为Gradle项目,检查build.gradle依赖配置:<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>4.11.0</version> <scope>test</scope> </dependency>testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-core:4.11.0' - 同步构建路径
右键项目 → Build Path → Configure Build Path,查看Libraries标签下Test类路径是否存在Mockito jar包。Maven项目执行右键 → Maven → Update Project,Gradle项目执行右键 → Gradle → Refresh Gradle Project,强制同步依赖到构建路径。 - 检查注解与导入写法
确认测试类导入的是正确的全限定类,注解写法无误:import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class 你的测试类名 { // 测试逻辑 } - 版本兼容适配
若使用JUnit5(Jupiter),无需使用MockitoJUnitRunner,改用@ExtendWith(MockitoExtension.class)注解,同时引入对应依赖:<dependency> <groupId>org.mockito</groupId> <artifactId>mockito-junit-jupiter</artifactId> <version>4.11.0</version> <scope>test</scope> </dependency> - 清理缓存重编译
点击Eclipse顶部菜单Project → Clean,选中对应项目清理编译缓存后,重新运行测试即可。
内容的提问来源于stack exchange,提问作者Victor Ekpo
相关产品推荐
相关产品推荐

