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

  • 1、首先解决Junit5报错

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

添加依赖

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没有运行(下面解答)。
重现错误,你可以添加如下依赖(如果不考虑重现错误,可以跳过此步,此依赖不是必需添加):

implementation 'org.junit.jupiter:junit-jupiter-engine:5.8.2'

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

	@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的对象也装载进来了。

你可能感兴趣的:(Bug,Java,bug,spring,boot,junit)