SuperAPI AI 工具集

using-robolectric-correctly

通用与其它

查看项目

更新于 10-16 03:39

技能介绍

用途:在 JVM 上以 Robolectric 运行依赖 android.* 的单元测试,速度比模拟器快 10-100 倍。Robolectric 用纯 Java 的 shadow 替换系统类,但不是模拟器:没有真实 RenderThread、Binder 或 GPU。

主要能力:锁定运行器选择、@Config 矩阵、Looper 排空步骤,以及 AGP 7.2+ 的 sharedTest 问题。

使用方式:依赖需包含 junit:junit:4.13.2、org.robolectric:robolectric:4.x、androidx.test:core:1.7.0、androidx.test.ext:junit:1.3.0。必须在 android.testOptions.unitTests 中设置 includeAndroidResources = true。运行器默认用 androidx.test.ext.junit.runners.AndroidJUnit4(JVM 上委派 Robolectric,设备上走真实运行器);仅当测试直接使用 shadowOf(Looper.getMainLooper()).idle() 等 Robolectric 专有 API 或需要 ParameterizedRobolectricTestRunner 时才用 org.robolectric.RobolectricTestRunner。@Config 可设 sdk、minSdk、qualifiers、application,方法级覆盖类级;sdk 与 minSdk/maxSdk 不能同时出现。默认 LooperMode.PAUSED 不会自动执行 post 的 Runnable,断言前需 shadowOf(Looper.getMainLooper()).idle() 或 ShadowLooper.runUiThreadTasksIncludingDelayedTasks()。

适用场景:被测类导入 android.* 且希望在 JVM 秒级测试;出现 Method not mocked 或 Resources$NotFoundException;需要同一测试源在 JVM 与设备上运行。

限制:无 android.* 导入的纯 Kotlin 测试不应使用;像素渲染、涟漪动画、无障碍服务、RenderThread 时序、GPU/Skia 行为需在模拟器或设备上运行。AGP 7.2+ 不可将同一源目录加入多个 source set,应改用 androidHostTest + androidDeviceTest 或独立 Gradle 模块。Robolectric 4.x 支持 SDK 21 至最新稳定版,Compose 宿主测试下限为 23。