Gradle Kotlin项目需显式配置三要素才能运行JUnit 5测试:testImplementation提供API、testRuntimeOnly提供junit-jupiter-engine、tasks.test { useJUnitPlatform() }启用平台;测试类须置于src/test/kotlin且以Test结尾,方法名含空格需用反引号包裹;Android项目还需android-junit5插件及includeAndroidResources=true。

Gradle Kotlin项目默认不带JUnit 5运行能力,必须显式声明依赖和启用测试平台——否则./gradlew test会静默跳过所有测试,或者报No tests found。
build.gradle.kts里必须配齐三样东西
只加testImplementation("org.junit.jupiter:junit-jupiter")不够,缺一不可:
-
testImplementation提供注解和断言(如@Test、assertEquals) -
testRuntimeOnly提供引擎实现(junit-jupiter-engine),没它JUnit Platform就找不到执行器 -
test { useJUnitPlatform() }告诉Gradle用JUnit 5平台发现并运行测试,而不是默认的JUnit 4兼容模式
完整写法示例:
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter:5.11.2")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.11.2")
}
tasks.test {
useJUnitPlatform()
}
Kotlin测试类命名和方法写法有隐含要求
Gradle + JUnit 5 能识别Kotlin测试类,但有两个易被忽略的条件:
- 测试类必须放在
src/test/kotlin下,且文件名以Test结尾(如CalculatorTest.kt),否则useJUnitPlatform()可能扫描不到 - 测试方法名若含空格或自然语言,必须用反引号包裹:
fun `should throw on negative input`();直接写shouldThrowOnNegativeInput也行,但前者可读性高,且不会因Kotlin命名规范被误判为非测试方法 - 别漏掉
import org.junit.jupiter.api.Test——Kotlin不自动导入Jupiter注解,IDE有时会帮你加,但命令行跑./gradlew test时失败往往就卡在这行缺失
Android项目要多加一个插件
普通JVM Kotlin项目到上一步就能跑通,但Android项目额外需要android-junit5插件,因为AGP默认禁用JUnit 5平台:
- 在
build.gradle.kts(Project级)添加插件依赖:classpath("de.mannodermaus.gradle.plugins:android-junit5:1.9.0.0") - 在Module级
build.gradle.kts中启用:plugins { id("de.mannodermaus.android-junit5") } - Android还要求
testOptions.unitTests.includeAndroidResources = true才能访问R资源,否则@Test里调用Context.getString()会NPE
常见错误:test任务没输出、IDE能跑但CLI报错
最典型的症状是./gradlew test返回BUILD SUCCESSFUL但零测试执行——根本原因是useJUnitPlatform()没生效,或者引擎jar没进runtime classpath。排查顺序:
- 运行
./gradlew test --info | grep "test platform",确认输出里有Using JUnit Platform launcher - 检查
./gradlew dependencies --configuration testRuntimeClasspath,确认junit-jupiter-engine出现在列表中 - 如果用Kotlin DSL,别写
testRuntimeOnly("org.junit.jupiter:junit-jupiter:5.11.2")——这个坐标只含API,不含引擎,必须拆成testImplementation+testRuntimeOnly两个条目
真正卡住人的地方,往往不是语法写错,而是testRuntimeOnly漏了、或useJUnitPlatform()写在了错误的tasks作用域里(比如写在tasks.withType<test></test>外层,没绑定到实际的test任务上)。


















