bug:Junit5报错,@SpringBootTest没有运行

  • 1、首先解决Junit5报错

java.lang.NoClassDefFoundError: org/junit/platform/launcher/core/LauncherFactory

添加依赖

sh 复制代码
implementation 'org.junit.platform:junit-platform-launcher:1.8.2'

java.lang.IllegalArgumentException: Error: test loader org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader not found:

这个报错也可以添加依赖解决,但添加依赖后,就算Junit5再次运行通过,你会发现@Autowired自动装载的对象为null,调用对象会报NullPointerException空指针异常。其实就是@SpringBootTest没有运行(下面解答)。

重现错误,你可以添加如下依赖(如果不考虑重现错误,可以跳过此步,此依赖不是必需添加):

sh 复制代码
implementation 'org.junit.jupiter:junit-jupiter-engine:5.8.2'

在测试代码中添加如下,查看springboot是否启动

java 复制代码
	@Autowired
	private ApplicationContext applicationContext;
	
	...
	System.out.println(applicationContext);
	...

如果junit-jupiter-engine的依赖版本过低,还会报另一种错:

org/junit/jupiter/api/extension/ScriptEvaluationException

  • 2、@SpringBootTest没有运行
    导致@SpringBootTest没有运行的原因是测试类没有放在规定路径下。当我们一开始创建springboot工程时就会自动创建一个默认的测试类,规定路径在src/test/java下。我们测试类放在这个测试类同级的包下时,再run with-》Junit Test。我们会发现SpringBoot打印了很多后台信息,恭喜你成功了。到此,@Autowired的对象也装载进来了。
相关推荐
砍材农夫5 小时前
spring-ai|Spring‑AI 2.0.0 新特性 + 入门教程
spring boot·spring·spring cloud
小强库计算机毕业设计7 小时前
SpringBoot+Vue3 学生宿舍管理系统实战
java·spring boot·后端·vue·学生宿舍管理系统
重庆小透明11 小时前
深入探寻微服务【第五篇微服务限流实战】
微服务·junit·架构
深念Y16 小时前
Opencode Event 表写入优化方案
数据库·人工智能·ai·node.js·bug·优化·opencode
不是光头 强16 小时前
SpringBoot事务优化与状态机实战
java·spring boot·后端
難釋懷17 小时前
Nginx-Openresty
nginx·junit·openresty
Flittly1 天前
【雕虫大技】Agent 动态 Skill 供应链安全加固(三):输出校验与治理闭环实战
java·spring boot·spring
姚青&2 天前
Bug基本概念
bug
小强库计算机毕业设计2 天前
基于 Spring Boot + Vue3 的校园管理系统
java·spring boot·后端·项目实战·管理系统·技术分享·校园管理系统实战
AI多Agent协作实战派2 天前
AI多Agent协作系统实战(三十九):AI修对了Bug,却越了权——自动化团队的第一条铁律
人工智能·自动化·bug