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的对象也装载进来了。
相关推荐
你我约定有三4 小时前
MyBatis--缓存详解
spring boot·缓存·mybatis
MZ_ZXD0014 小时前
springboot汽车租赁服务管理系统-计算机毕业设计源码58196
java·c++·spring boot·python·django·flask·php
奶糖 肥晨7 小时前
解决 UniApp 自定义弹框被图片或 Canvas 覆盖的 Bug
uni-app·bug
Monly2110 小时前
RabbitMQ:生产者可靠性(生产者重连、生产者确认)
spring boot·rabbitmq·java-rabbitmq
ankleless11 小时前
Spring Boot 实战:从项目搭建到部署优化
java·spring boot·后端
白露与泡影14 小时前
SpringBoot前后端token自动续期方案
spring boot·后端·状态模式
还听珊瑚海吗17 小时前
基于WebSocket和SpringBoot聊天项目ChatterBox测试报告
spring boot·websocket·网络协议
Monly2117 小时前
RabbitMQ:SpringAMQP Topic Exchange(主题交换机)
spring boot·rabbitmq·java-rabbitmq
Pitayafruit1 天前
Spring AI 进阶之路04:集成 SearXNG 实现联网搜索
spring boot·后端·ai编程