Spring Boot项目在Idea上 用 Junit5 单元测试报错

问题描述

用spring boot 2.2.X 版本进行项目搭建,pom文件配置以下:java

<properties>
    <java.version>1.8</java.version>
</properties>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.1.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>org.springframework.boot</groupId>  
 <artifactId>spring-boot-maven-plugin</artifactId>  
 </plugin> </plugins></build>

单元测试类代码以下:web

import com.example.test.AbstractTest;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

@SpringBootTest(classes = {Application.class})
class ApplicationTests {

    @Resource(name = "test1")
    private AbstractTest test1;

    @Resource(name = "test2")
    private AbstractTest test2;

    @Test
    public void showTest() {

        test1.show();

        test2.show();
    }

}

在进行单元测试时,程序报错,错误提示以下:spring

Exception in thread "main" java.lang.NoSuchMethodError: org.junit.platform.commons.util.ReflectionUtils.getDefaultClassLoader()Ljava/lang/ClassLoader;
    at org.junit.platform.launcher.core.ServiceLoaderTestEngineRegistry.loadTestEngines(ServiceLoaderTestEngineRegistry.java:30)
    at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.createListeners(JUnit5IdeaTestRunner.java:39)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:49)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

排查过程

网上找了不少相似的错误,可能是说Junit4 和Junit5 之间依赖冲突了,按照网友的一些解决思路进行修改,如删除Junit5 的相关依赖,发现并无解决问题,后再Junit5 官网上发现,官网明确指出在IntelliJ IDEA 中使用Junit5 时,最好是2017.3版本以后,而我使用的正是2017.1的版本。
IntelliJ IDEA 跑Junit5 版本json

解决问题

我在更换了新的IDEA 后,发现问题果真解决了。若是不想更新IDEA ,则能够按照官网所描述的步骤进行操做,同样能够解决问题。api

总结

在遇到这些问题时,若是有官方文档,最好先去官网上看一看,也许官网已经提了这些问题,也给出了解决方案,避免无头苍蝇通常在网上乱找。intellij-idea