junit 5 在命令行选择测试引擎主要依赖 org.junit.platform.console.consolelauncher,通过 --select-class、--select-method 或 --scan-classpath 等参数指定目标。多引擎执行配置的核心在于确保类路径中同时包含 junit jupiter(原生引擎)和 junit vintage(兼容旧版引擎),并正确设置启动器依赖。

如何通过命令行参数精确选择特定测试类或方法?
使用 ConsoleLauncher 时,可以通过 --select-class 指定完整类名,或通过 --select-method 指定类名和方法名来运行单个测试。这些参数直接传递给平台启动器,引擎会根据测试注解自动匹配执行。

java -cp "junit-platform-console-standalone-1.10.0.jar;src/test/java" org.junit.platform.console.ConsoleLauncher --select-class com.example.MyTest --details=verbose
上述命令将仅执行 com.example.MyTest 中的所有测试,并输出详细日志。若需执行特定方法,可替换为 --select-method com.example.MyTest#testSpecificCase。这种方式避免了全量扫描,适合快速验证单个用例。
如何配置环境以支持 JUnit 4 和 JUnit 5 混合执行?
要同时执行 JUnit 4 和 JUnit 5 测试,必须在类路径中包含 junit-vintage-engine。Jupiter 引擎默认处理 @Test (org.junit.jupiter.api.Test),而 Vintage 引擎处理 @Test (org.junit.Test)。只要两者都在 classpath 中,启动器会自动发现并分发任务。

java -cp "junit-platform-console-standalone-1.10.0.jar;junit-vintage-engine-5.10.0.jar;junit-4.13.2.jar;hamcrest-core-1.3.jar;src/test/java" org.junit.platform.console.ConsoleLauncher --scan-classpath src/test/java
该命令通过 --scan-classpath 扫描指定目录下的所有测试。由于引入了 Vintage 引擎,它不仅能识别 JUnit 5 的注解,还能兼容 JUnit 4 的测试类。注意,junit-vintage-engine 必须与 ConsoleLauncher 版本兼容,通常建议从同一发行版下载。
当测试类继承自 TestCase 时,Vintage 引擎如何处理其生命周期?
对于继承自 junit.framework.TestCase 的旧式测试,Vintage 引擎会将其视为标准 JUnit 3/4 测试处理。它会调用 setUp() 和 tearDown() 方法,并捕获 AssertionFailedError 作为失败信号。这与 JUnit 5 的 @BeforeEach 和 @AfterEach 语义不同,但引擎内部做了适配。

















