使用Maven导入Junit5依赖时的注意事项
原先我的Maven中Junit5依赖如下:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
SaleMachineTest 测试类的import无问题:

但是在运行 ConsoleOutputTest 测试类代码时
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ConsoleOutputTest {
@Test
public void testConsoleOutput() {
// 1. 创建一个 ByteArrayOutputStream 来捕获输出内容
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
// 2. 保存原始的 System.out 用于断言后恢复原始流
PrintStream originalOut = System.out;
try {
// 3. 将 System.out 重定向到 ByteArrayOutputStream
System.setOut(new PrintStream(outContent));
// 4. 调用会打印到控制台的方法
System.out.println("Hello, World!");
// 5. 获取捕获的输出内容并断言
String output = outContent.toString().trim();
assertEquals("Hello, World!", output);
} finally {
// 6. 恢复原始的 System.out(重要!)
System.setOut(originalOut);
}
}
}
会报如下错误:
Exception in thread "main" java.lang.NoSuchMethodError: 'java.lang.String org.junit.platform.engine.discovery.MethodSelector.getMethodParameterTypes()'
at com.intellij.junit5.JUnit5TestRunnerUtil.loadMethodByReflection(JUnit5TestRunnerUtil.java:127)
at com.intellij.junit5.JUnit5TestRunnerUtil.buildRequest(JUnit5TestRunnerUtil.java:102)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:43)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)
经查询相关文章,将Junit5依赖改为如下(指定版本):
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.13.4</version>
<scope>test</scope>
</dependency>
ConsoleOutputTest 测试类即可运行,但是发现 SaleMachineTest 测试类的导包出现问题


将Junit5依赖改回去,则 SaleMachineTest 测试类的导包无问题,但是 ConsoleOutputTest 测试类运行又会报错。
最后经过查看依赖项,发现导包有误

将Junit5依赖改为如下,则两个测试类都能运行
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.13.4</version>
<scope>test</scope>
</dependency>
浙公网安备 33010602011771号