3. Gradle 依赖配置:测试依赖、Mockito、JUnit、AndroidX Test、Robolectric
测试基础设施的搭建从 Gradle 依赖配置 开始。Android 项目的测试分为单元测试和仪器化测试,分别运行在本地 JVM 或物理设备/模拟器上。本章将逐一拆解每个核心库的作用、版本搭配原则,并给出可直接复用的完整配置模板。
目标:完成本章后,你能够独立为任意 Android 模块编写正确的测试依赖声明,避免版本冲突与构建失败。
3.1 测试依赖架构全景
下图展示了测试执行时各组件之间的编译与运行关系。单元测试阶段,JUnit + Mockito 运行在 JVM 上;仪器化测试阶段,AndroidX Test + Robolectric 提供 Android 框架模拟。
3.2 核心依赖详解
| 库名 | 配置域 | 作用 | 典型版本(2024) |
|---|---|---|---|
| JUnit 4 / 5 | testImplementation | Java/Kotlin 单元测试框架,提供断言和测试运行器 | 4.13.2 / 5.10.0 |
| Mockito | testImplementation | Mock 框架,隔离依赖对象,验证交互 | 5.7.0 |
| AndroidX Test Core | androidTestImplementation | 提供 Android 测试基础 API,如 ApplicationProvider | 1.5.0 |
| AndroidX Test Runner | androidTestImplementation | InstrumentationTestRunner,管理测试执行 | 1.5.0 |
| AndroidX Test Ext:JUnit | androidTestImplementation | JUnit 与 AndroidX 测试规则绑定 | 1.1.5 |
| Robolectric | testImplementation | 模拟 Android 框架,在 JVM 上运行仪器化测试 | 4.11.1 |
| Espresso | androidTestImplementation | UI 交互测试框架 | 3.5.1 |
版本原则:所有 AndroidX Test 库的版本应保持一致,使用 BOM 可简化管理。Mockito 3.x 是 Kotlin 最稳定选择,Mockito 5.x 支持 Android 单元测试内联 Mock。
3.3 标准配置模板
以下配置可直接用于模块级 build.gradle.kts 或 build.gradle。请根据项目需要选择对应库。
dependencies {
// 单元测试(在 JVM 上运行)
testImplementation("junit:junit:4.13.2")
testImplementation("org.mockito:mockito-core:5.7.0")
// 如果使用 Kotlin,建议添加 mockito-kotlin 扩展
testImplementation("org.mockito.kotlin:mockito-kotlin:5.1.0")
// Robolectric(在单元测试中模拟 Android 环境)
testImplementation("org.robolectric:robolectric:4.11.1")
// 仪器化测试(在设备/模拟器上运行)
androidTestImplementation("androidx.test:core:1.5.0")
androidTestImplementation("androidx.test:runner:1.5.0")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
// 可选:Fragment 测试场景
debugImplementation("androidx.fragment:fragment-testing:1.6.2")
}
3.4 配置编写注意事项
- 配置域区分:
testImplementation仅对src/test生效;androidTestImplementation仅对src/androidTest生效;debugImplementation仅在 debug 构建变体下可用。 - Robolectric 与 AndroidX 混合:若同时在
testImplementation中使用 Robolectric 和 AndroidX Test 库,务必确保版本匹配(建议统一使用 BOM 4.xx)。 - Kotlin 编译器版本:Mockito 5.x 要求 Kotlin 1.7+,低于该版本会导致编译失败。
3.5 调试技巧与常见错误
错误 1:java.lang.NoClassDefFoundError — 通常因缺少
androidx.test:core 或版本冲突。运行 ./gradlew :app:dependencies --configuration debugAndroidTestCompileClasspath 查看依赖树。
错误 2:Mockito 无法 Mock 最终类 — 在
src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker 中添加一行:
mock-maker-inline
警告:不要同时声明多个版本的 JUnit。若使用 JUnit 5,请移除所有 JUnit 4 依赖,或通过
@RunWith(JUnit4::class) 桥接。3.6 性能优化建议
- 使用 BOM 统一版本:为 AndroidX Test 引入 BOM,避免逐个升级:
dependencies { implementation(platform("androidx.test:test-bom:1.5.0")) androidTestImplementation("androidx.test:core") androidTestImplementation("androidx.test:runner") } - 按需配置 Mockito Inline:仅在需要 Mock 最终类时启用 inline mock,否则使用默认代理模式,测试运行速度更快。
- 缓存测试类路径:在
gradle.properties中设置org.gradle.parallel=true和org.gradle.caching=true,加速多模块项目的测试编译。