STS导入Spring Boot项目运行JUNIT 4提示No tests found问题求助
解决方案
- 先排查依赖冲突:Spring Boot 2.2及以上版本默认集成JUnit 5(Jupiter)作为测试框架,start.spring.io生成的项目默认引入的
spring-boot-starter-test内置JUnit 5依赖,和你单独添加的JUnit 4依赖会产生冲突,需先排除JUnit 5相关包:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <!-- 排除默认JUnit 5依赖 --> <exclusions> <exclusion> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> </exclusion> <exclusion> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> </exclusion> </exclusions> </dependency> <!-- 统一使用JUnit 4依赖 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency>
- 强制更新Maven依赖:STS中右键项目,选择
Maven > Update Project,勾选Force Update of Snapshots/Releases,确认后等待依赖更新完成,即可解决org.junit.Test导入报错的问题。 - 测试类正确写法:无需继承
TestCase,标准JUnit 4 + Spring Boot测试类写法如下:
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class DevopsApplicationTests { @Test public void contextLoads() { // 此处填写测试逻辑 } }
- 调整运行配置:右键测试类选择
Run As > Run Configurations,找到对应JUnit运行项,确认Test runner选择为JUnit 4,保存后运行即可解决找不到测试的问题。
备选方案(推荐)
如果无强制使用JUnit 4的要求,直接使用默认JUnit 5框架更简单,无需修改依赖,仅需调整测试类注解:
import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class DevopsApplicationTests { @Test void contextLoads() { // 测试逻辑 } }
运行时选择JUnit 5作为测试运行器即可正常执行。
内容的提问来源于stack exchange,提问作者user630702
相关产品推荐
相关产品推荐

