用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