1、现象:
今天起了一个Springboot项目,执行test抛了一个异常
pom.xml中test相关的依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
相关的java代码
@SpringBootTest
public class ScrewtestApplicationTests {
@Autowired
ApplicationContext applicationContext;
@Test
public void contextLoads() {
...
...
...
邮件执行Run进行test测试,没有正常执行,执行异常,异常信息如下图
No tests were found
Exception in thread "main" java.lang.NoSuchMethodError: org.junit.platform.commons.util.ReflectionUtils.getDefaultClassLoader()Ljava/lang/ClassLoader;
2、原因:
查找了相关的说明总结如下:
IntelliJ IDEA 中使用Junit5 时,需要Idea2017.3版本之后,之前的版本不支持 JUnit5.
springboot 默认是用 junit5来执行的 如果直接调用就会抛出异常java.lang.NoSuchMethodError: org.junit.platform.commons.util.ReflectionUtils.getDefaultClassLoader()Ljava/lang/ClassLoader;
我的idea的版本zheng正好是2017.1
3、解决方案:
解决方案一:将IDEA升级到2017.3之后的版本,则升级IDEA
解决方案二:使用 JUnit4
我对我的的idea各种配置以及界面已经很熟悉了,第一种方案的代价太大,不至于因为一个小的项目就取升级idea的版本,我选择的是方案二
别人遇到的坑可能跟你的现象是一样的,但他的解决方案不一定适合你,跟很多因素有关,比如idea的具体版本,springboot的版本,jar包冲突等,我的也调试了半天才正常,但别人的思路对你处理问题肯定是一个借鉴
我的调整如下:
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<!--排除JUnit5的相关api-->
<exclusions>
<exclusion>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--引入JUnit4-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
排除JUnit5,并引入Junit4
相关java代码调整
修改测试类。增加 RunWith 注解,引入 org.junit.Test。
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ScrewtestApplicationTests {
@Autowired
ApplicationContext applicationContext;
@Test
public void contextLoads() {
...
...
...
执行Run成功
最近浏览





