java.lang.NoSuchMethodError 当 运行 使用 Junit 5 测试时

java.lang.NoSuchMethodError when run test with Junit 5

我创建了一个简单的测试来尝试 Junit 5:

import org.junit.jupiter.api.Test;
public class MyTest {

    @Test
    public void testJupiter() {
        System.out.println("test");
    }
}

这是我使用的依赖:

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.0.0</version>
            <scope>test</scope>
        </dependency>

下一个是堆栈跟踪:

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)

知道哪里出了问题吗?

除了依赖,你的pom.xml里有没有配置JUnit5插件?它应该看起来像这样(取自 the docs):

...
<build>
    <plugins>
        ...
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.19</version>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-surefire-provider</artifactId>
                    <version>1.0.0</version>
                </dependency>
                <dependency>
                    <groupId>org.junit.jupiter</groupId>
                    <artifactId>junit-jupiter-engine</artifactId>
                    <version>5.0.0</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>
...
<dependencies>
    ...
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.0.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>
...

我看到您正在使用仅支持特定版本的 jUnit5 的 IntelliJ。

Junit5 - running tests in IntelliJ

尝试例如

<version>5.0.0-M4</version>