Gradle Java项目提示“缺少测试引擎”本质是junit-jupiter-engine未进入运行时classpath或IDE未识别:需显式声明testRuntimeOnly依赖、确保API与Engine版本一致、IDE Run Configuration中Test kind必须设为JUnit5,且自定义sourceSet须同步配置对应runtime依赖。

Gradle Java项目提示“缺少测试引擎”,基本就是 junit-jupiter-engine 没被正确加载或识别——不是没加依赖,而是加了但没进运行时 classpath,或者 IDE 没认出它是 JUnit 5 引擎。
build.gradle 里 testRuntimeOnly 忘了加 junit-jupiter-engine
JUnit 5 分三块:API(写测试用)、Engine(执行测试用)、Platform(启动器)。junit-jupiter 只含 API + Engine,但 Gradle 默认把 testImplementation 的依赖只放编译期,不自动带进运行时。所以即使写了 testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2',./gradlew test 仍可能报 TestEngine with ID 'junit-jupiter' failed to discover tests。
- 必须显式声明运行时引擎:
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.10.2' - 别用
testImplementation替代它——那是错的,会导致类加载失败 - 版本号务必和 API 一致,混用 5.9.x 和 5.10.x 容易触发
NoClassDefFoundError
IDEA 里 Run Configuration 选错 Test kind
命令行 ./gradlew test 成功,但 IDEA 右键 Run 却报 ClassNotFoundException: org.junit.jupiter.api.Test,八成是 IDE 没切到 JUnit 5 引擎。
- 打开 Run → Edit Configurations…
- 左侧选中你的测试配置(比如
ExampleTest) - 右侧找
Test kind下拉框,必须选JUnit5,不能是JUnit4或Pattern - 如果下拉列表里压根没有
JUnit5选项,说明 IDEA 没检测到junit-jupiter-engine在 classpath —— 回头检查 build.gradle 是否漏了testRuntimeOnly那一行
用了自定义 sourceSet(如 dbtest)但没配 test task 依赖
如果你按规范拆了集成测试目录(比如 src/dbtest/java),又没手动把 dbtest 的运行时依赖连上 junit-jupiter-engine,Gradle 就不会把它加载进测试执行环境。
- 在
sourceSets块里定义完dbtest后,必须额外加 task 配置: tasks.named('test').configure { dependsOn tasks.named('dbtest') }- 且确保
dbtestImplementation和dbtestRuntimeOnly都包含对应版本的junit-jupiter和junit-jupiter-engine - 否则
./gradlew dbtest会静默跳过所有测试,不报错也不执行
最常被忽略的是:Gradle 的依赖作用域比 Maven 更严格,testImplementation 不等于“测试时可用”,它只管编译;真正决定“能不能跑起来”的是 testRuntimeOnly —— 这个边界一旦模糊,引擎就消失。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











