using-robolectric-correctly
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUsing Robolectric Correctly — Android On The JVM, Without The Footguns
正确使用 Robolectric——在 JVM 上测试 Android,避免常见陷阱
Robolectric simulates Android on the JVM by swapping in pure-Java reimplementations of system classes ("shadows"). It is fast (10-100x vs an emulator) but not an emulator: no real , no real Binder, no real GPU. This skill locks down the runner choice, the matrix, the looper draining ritual, and the AGP 7.2+ sharedTest gotcha. Compose-on-Robolectric specifics live in .
RenderThread@Config../../../compose/synchronization/controlling-the-test-clock/SKILL.mdRobolectric 通过将系统类替换为纯 Java 重新实现(这些实现称为 “shadows”)来在 JVM 上模拟 Android。它的速度很快(比模拟器快 10-100 倍),但它不是模拟器:没有真实的 、真实的 Binder 或真实的 GPU。本 skill 明确了运行器选择、 矩阵、Looper 清空流程,以及 AGP 7.2+ 的 sharedTest 陷阱。在 Robolectric 上使用 Compose 的具体注意事项位于 。
RenderThread@Config../../../compose/synchronization/controlling-the-test-clock/SKILL.mdWhen to use this skill
何时使用此 skill
- The class under test imports (Context, Resources, View, PackageManager, Looper) and the developer wants to test it on the JVM in seconds, not on an emulator in minutes.
android.* - A unit test fails with (the bare-Android-jar default) — the developer needs Robolectric's shadows.
RuntimeException: Method ... not mocked - A unit test fails with —
Resources$NotFoundExceptionis missing.testOptions.unitTests.includeAndroidResources - The developer asks "AndroidJUnit4 vs RobolectricTestRunner — which?".
- A /
Handler.postDelayedqueue does not advance under Robolectric's defaultLooper.LooperMode.PAUSED - The developer asks how to run the same test source on JVM and on a device (/
sharedTest+androidHostTest).androidDeviceTest - Build error after AGP 7.2+: "Source directory ... already added to source set", caused by the classic
sharedTestsharing pattern.srcDir
- 被测类导入了 (Context、Resources、View、PackageManager、Looper),开发者希望在几秒内完成 JVM 测试,而不是花几分钟运行模拟器。
android.* - 单元测试因 而失败(默认的 bare Android jar 所导致)——开发者需要使用 Robolectric 的 shadows。
RuntimeException: Method ... not mocked - 单元测试因 而失败——缺少
Resources$NotFoundException。testOptions.unitTests.includeAndroidResources - 开发者询问“AndroidJUnit4 vs RobolectricTestRunner——该选哪个?”。
- 在 Robolectric 默认的 下,
LooperMode.PAUSED/Handler.postDelayed队列不会自动推进。Looper - 开发者询问如何在 JVM 和设备上运行相同的测试源文件(/
sharedTest+androidHostTest)。androidDeviceTest - 使用 AGP 7.2+ 后出现构建错误:“Source directory ... already added to source set”,其原因是传统的
sharedTest共享模式。srcDir
When NOT to use this skill
何时不应使用此 skill
- The class under test has zero imports. Robolectric pays a 1-3 s class-load tax for nothing — use plain JUnit4. See
android.*.../../runner/configuring-junit4-on-android/SKILL.md - The test verifies pixel correctness, ripple animations, screenshot diffs, accessibility services, or timing. Run on an emulator/device. See
RenderThread.../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md - The test is about coroutines + and does not need framework Android. Use
runTest.../../coroutines/testing-coroutines-with-runtest/SKILL.md - The test is about Compose UI rendering. The host-test environment is set up by and the clock semantics live in
../../../compose/setup/configuring-test-dependencies/SKILL.md.../../../compose/synchronization/controlling-the-test-clock/SKILL.md
- 被测类没有导入任何 。使用 Robolectric 会白白增加 1-3 秒的类加载开销——请使用普通 JUnit4。参见
android.*。../../runner/configuring-junit4-on-android/SKILL.md - 测试需要验证像素正确性、ripple 动画、截图差异、无障碍服务或 时序。请在模拟器或设备上运行。参见
RenderThread。../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md - 测试关注协程与 ,且不需要 Android 框架。请使用
runTest。../../coroutines/testing-coroutines-with-runtest/SKILL.md - 测试关注 Compose UI 渲染。宿主测试环境由 配置,时钟语义位于
../../../compose/setup/configuring-test-dependencies/SKILL.md。../../../compose/synchronization/controlling-the-test-clock/SKILL.md
Prerequisites
前置条件
kotlin
testImplementation("junit:junit:4.13.2")
testImplementation("org.robolectric:robolectric:4.x")
testImplementation("androidx.test:core:1.7.0") // ApplicationProvider works on both runtimes
testImplementation("androidx.test.ext:junit:1.3.0") // androidx.test.ext.junit.runners.AndroidJUnit4( §G.1; R7.)
docs/CORPUS.mdgradle
android {
testOptions {
unitTests {
includeAndroidResources = true // non-negotiable
}
}
}includeAndroidResourcesR.*Resourcesres/Robolectric 4.x supports SDKs 21 through the latest stable. The androidx Compose host tests pin a floor of 23 — quote it as a single source of truth:
kotlin
// androidx/compose/ui/ui-test/src/androidHostTest/.../Constants.kt
internal const val RobolectricMinSdk = 23(R7.)
kotlin
testImplementation("junit:junit:4.13.2")
testImplementation("org.robolectric:robolectric:4.x")
testImplementation("androidx.test:core:1.7.0") // ApplicationProvider works on both runtimes
testImplementation("androidx.test.ext:junit:1.3.0") // androidx.test.ext.junit.runners.AndroidJUnit4( §G.1;R7。)
docs/CORPUS.mdgradle
android {
testOptions {
unitTests {
includeAndroidResources = true // non-negotiable
}
}
}如果任何测试(或测试加载的任何类)访问 、、布局、主题或 中的内容,就必须设置 。如果不设置,测试启动时的资源查找会抛出异常(R7)。
R.*Resourcesres/includeAndroidResourcesRobolectric 4.x 支持 SDK 21 至最新的稳定版本。androidx Compose 宿主测试将下限固定为 23——应将其作为单一事实来源引用:
kotlin
// androidx/compose/ui/ui-test/src/androidHostTest/.../Constants.kt
internal const val RobolectricMinSdk = 23(R7。)
Runner choice — AndroidJUnit4 vs RobolectricTestRunner
运行器选择——AndroidJUnit4 vs RobolectricTestRunner
Two runners work; they read identically.
@Config| Runner | When |
|---|---|
| Default. A router: delegates to Robolectric on JVM and to the real |
| Only when the test must never run on a device — e.g. uses Robolectric-specific shadow APIs like |
(R7; §G.6.)
docs/CORPUS.mdkotlin
import androidx.test.ext.junit.runners.AndroidJUnit4
@RunWith(AndroidJUnit4::class)
@Config(minSdk = 23)
class FooTest { /* runs under Robolectric on JVM, real runner on device */ }
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class LooperBoundTest { /* uses ShadowLooper APIs directly — JVM only */ }CRITICAL: (the runner package, not ) is ( §G.2). Always import from .
androidx.test.runner.AndroidJUnit4ext.junit.runners@Deprecateddocs/CORPUS.mdandroidx.test.ext.junit.runners两种运行器都可用,并且会以相同方式读取 。
@Config| 运行器 | 使用场景 |
|---|---|
| 默认选择。 它是一个路由器:在 JVM 上委托给 Robolectric,在设备上委托给真实的 |
| 仅当测试绝不能在设备上运行时使用——例如直接使用 Robolectric 专属 shadow API,如 |
(R7; §G.6。)
docs/CORPUS.mdkotlin
import androidx.test.ext.junit.runners.AndroidJUnit4
@RunWith(AndroidJUnit4::class)
@Config(minSdk = 23)
class FooTest { /* runs under Robolectric on JVM, real runner on device */ }
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class LooperBoundTest { /* uses ShadowLooper APIs directly — JVM only */ }关键:(runner 包,而不是 )已标记为 ( §G.2)。始终从 导入。
androidx.test.runner.AndroidJUnit4ext.junit.runners@Deprecateddocs/CORPUS.mdandroidx.test.ext.junit.runners@Config — sdk, qualifiers, application
@Config——sdk、qualifiers、application
@Configkotlin
// Single SDK
@Config(sdk = [Build.VERSION_CODES.UPSIDE_DOWN_CAKE])
class FooTest
// SDK matrix — runs once per listed SDK
@Config(sdk = [21, 28, 33])
class BarTest
// Range — runs once at the project's targetSdk if it is >= minSdk
@Config(minSdk = 23)
class BazTest
// Per-method override
class QuxTest {
@Test @Config(sdk = [Build.VERSION_CODES.TIRAMISU])
fun onTiramisuOnly() { /* ... */ }
@Test @Config(qualifiers = "fr-rFR-w820dp") // locale + screen
fun frenchLayout() { /* ... */ }
@Test @Config(qualifiers = "+night") // additive: keep, force night
fun darkColors() { /* ... */ }
}
// Override the Application instance
@Config(application = MyTestApplication::class)
class WithFakeApp(R7.)
Constraint: and / cannot coexist on the same annotation. and may be combined.
sdkminSdkmaxSdkminSdkmaxSdkCI-time hot take: prefer on the commit gate; reserve multi-SDK matrices for the merge gate. Each SDK in the matrix re-runs the whole class.
@Config(sdk = [<one SDK>])@Configkotlin
// Single SDK
@Config(sdk = [Build.VERSION_CODES.UPSIDE_DOWN_CAKE])
class FooTest
// SDK matrix — runs once per listed SDK
@Config(sdk = [21, 28, 33])
class BarTest
// Range — runs once at the project's targetSdk if it is >= minSdk
@Config(minSdk = 23)
class BazTest
// Per-method override
class QuxTest {
@Test @Config(sdk = [Build.VERSION_CODES.TIRAMISU])
fun onTiramisuOnly() { /* ... */ }
@Test @Config(qualifiers = "fr-rFR-w820dp") // locale + screen
fun frenchLayout() { /* ... */ }
@Test @Config(qualifiers = "+night") // additive: keep, force night
fun darkColors() { /* ... */ }
}
// Override the Application instance
@Config(application = MyTestApplication::class)
class WithFakeApp(R7。)
限制: 与 / 不能出现在同一个注解中。 与 可以组合使用。
sdkminSdkmaxSdkminSdkmaxSdkCI 阶段的实用建议:提交门禁优先使用 ;多 SDK 矩阵则留给合并门禁。矩阵中的每个 SDK 都会重新运行整个测试类。
@Config(sdk = [<单个 SDK>])Shadows
Shadows
Shadows are JVM-friendly fakes for Android system classes. Robolectric ships hundreds; you can write your own with /. Common ones:
@Implements@Implementation| Shadow | Purpose |
|---|---|
| Inspect started services / broadcasts / granted permissions. |
| Capture |
| Advance / freeze |
| Drive message queues; |
| Add/remove packages, set system features, queryable intents. |
| Inspect scheduled alarms without firing them. |
| Inspect posted notifications and channels. |
| Add/remove |
| Register fake providers, observe inserts/queries. |
Shadows.shadowOf(realObject)kotlin
import androidx.test.core.app.ApplicationProvider
import org.robolectric.Shadows.shadowOf
import org.robolectric.shadows.ShadowPackageManager
val app: Application = ApplicationProvider.getApplicationContext()
val shadowPm: ShadowPackageManager = shadowOf(app.packageManager)
shadowPm.setSystemFeature(PackageManager.FEATURE_CAMERA_ANY, true)Shadows 是适合 JVM 环境的 Android 系统类 fake。Robolectric 内置了数百种 shadow,也可以使用 / 自行编写。常见 shadow 包括:
@Implements@Implementation| Shadow | 用途 |
|---|---|
| 检查已启动的服务、广播和已授予权限。 |
| 捕获 |
| 推进或冻结 |
| 驱动消息队列; |
| 添加或移除软件包、设置系统功能、查询 Intent。 |
| 在不触发闹钟的情况下检查计划任务。 |
| 检查已发布的通知和通知渠道。 |
| 为输入测试添加或移除 |
| 注册 fake provider,监听插入和查询。 |
Shadows.shadowOf(realObject)kotlin
import androidx.test.core.app.ApplicationProvider
import org.robolectric.Shadows.shadowOf
import org.robolectric.shadows.ShadowPackageManager
val app: Application = ApplicationProvider.getApplicationContext()
val shadowPm: ShadowPackageManager = shadowOf(app.packageManager)
shadowPm.setSystemFeature(PackageManager.FEATURE_CAMERA_ANY, true)Looper draining — the most-missed step
Looper 清空——最容易遗漏的一步
Robolectric's main looper is paused in the default runtime mode. Handler messages posted by the SUT do NOT run automatically. Drain explicitly:
LooperMode.PAUSEDkotlin
import android.os.Looper
import org.robolectric.Shadows.shadowOf
import org.robolectric.shadows.ShadowLooper
import java.time.Duration
// Drain everything currently queued on the main looper.
shadowOf(Looper.getMainLooper()).idle()
// Run delayed tasks too (postDelayed et al).
ShadowLooper.runUiThreadTasksIncludingDelayedTasks()
// Advance virtual time by N ms; only handlers due before that time fire.
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(500))(R7.)
This complements (and is independent from) Compose's . The Compose clock and the platform looper are separate. For Compose-on-Robolectric, drives the looper for you via — outside Compose, drain manually.
MainTestClock.advanceTimeBy(...)runComposeUiTest { … waitForIdle() }RobolectricIdlingStrategy在默认的 运行模式下,Robolectric 的主 Looper 会暂停。由 SUT 发布到 Handler 的消息不会自动执行。必须显式清空队列:
LooperMode.PAUSEDkotlin
import android.os.Looper
import org.robolectric.Shadows.shadowOf
import org.robolectric.shadows.ShadowLooper
import java.time.Duration
// Drain everything currently queued on the main looper.
shadowOf(Looper.getMainLooper()).idle()
// Run delayed tasks too (postDelayed et al).
ShadowLooper.runUiThreadTasksIncludingDelayedTasks()
// Advance virtual time by N ms; only handlers due before that time fire.
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(500))(R7。)
这与 Compose 的 相互补充,但两者彼此独立。Compose 时钟和平台 Looper 是两个不同的系统。对于在 Robolectric 上运行 Compose 的场景, 会通过 自动驱动 Looper;在 Compose 之外则需要手动清空。
MainTestClock.advanceTimeBy(...)runComposeUiTest { … waitForIdle() }RobolectricIdlingStrategysharedTest / androidHostTest / androidDeviceTest
sharedTest / androidHostTest / androidDeviceTest
The classic sharedTest pattern (per the 2021 Robolectric blog post) puts one source directory under both and :
testandroidTestgradle
// LEGACY — broken on AGP 7.2+
android {
sourceSets {
String dir = 'src/sharedTest/'
test { java.srcDirs += dir + 'java' }
androidTest { java.srcDirs += dir + 'java' }
}
}CRITICAL: starting with AGP 7.2+, you cannot put the same source directory into multiple source sets (Robolectric GitHub issue #7432; R7). The build fails with "Source directory ... already added to source set".
Modern alternatives (PREFERRED order):
- AndroidX-style KMP source sets — ->
commonTestvia the{androidHostTest, androidDeviceTest}plugin. Compose internally migrated to this:androidXMultiplatformgradlesourceSets { androidCommonTest { dependsOn(commonTest) } androidDeviceTest { dependsOn(androidCommonTest) } // instrumented APK androidHostTest { dependsOn(androidCommonTest) } // Robolectric on JVM } - Separate Gradle module that both and
testdepend on asandroidTest/testImplementation.androidTestImplementation - Symlink or copy sources at configuration time (least preferred — fragile).
Both and can use unchanged because is a router. Source-set wiring is .
androidHostTestandroidDeviceTest@RunWith(AndroidJUnit4::class)AndroidJUnit4../../../fundamentals/strategies/organizing-test-source-sets/SKILL.md经典的 sharedTest 模式( according to the 2021 Robolectric blog post)会将同一个源目录同时放入 和 :
testandroidTestgradle
// LEGACY — broken on AGP 7.2+
android {
sourceSets {
String dir = 'src/sharedTest/'
test { java.srcDirs += dir + 'java' }
androidTest { java.srcDirs += dir + 'java' }
}
}关键:从 AGP 7.2+ 开始,不能将同一个源目录放入多个 source set(Robolectric GitHub issue #7432;R7)。构建会因“Source directory ... already added to source set”而失败。
现代替代方案(按优先级排列):
- AndroidX 风格的 KMP source set——通过 插件,将
androidXMultiplatform映射到commonTest。Compose 内部已迁移到这种方式:{androidHostTest, androidDeviceTest}gradlesourceSets { androidCommonTest { dependsOn(commonTest) } androidDeviceTest { dependsOn(androidCommonTest) } // instrumented APK androidHostTest { dependsOn(androidCommonTest) } // Robolectric on JVM } - 独立的 Gradle module,并让 和
test分别通过androidTest/testImplementation依赖它。androidTestImplementation - 符号链接或复制源文件,并在配置阶段执行(最不推荐——容易失效)。
androidHostTestandroidDeviceTest@RunWith(AndroidJUnit4::class)AndroidJUnit4../../../fundamentals/strategies/organizing-test-source-sets/SKILL.mdWhen NOT to reach for Robolectric
何时不应使用 Robolectric
| Scenario | Where it belongs |
|---|---|
Pure Kotlin, no | Plain JUnit4 in |
| Pixel-correct rendering, screenshot tests | Emulator/device — |
| Accessibility service behavior | Emulator/device. Compose's |
| Emulator/device. |
| GPU/Skia behavior | Emulator/device. |
| 场景 | 应使用 |
|---|---|
纯 Kotlin,没有 | |
| 像素级正确的渲染、截图测试 | 模拟器或设备——只有在那里才有真实的 |
| 无障碍服务行为 | 模拟器或设备。Compose 的 |
| 模拟器或设备。 |
| GPU/Skia 行为 | 模拟器或设备。 |
Patterns
模式
Pattern: WRONG — RobolectricTestRunner for a test that should also run on device
模式:错误——对应当 also run on device 的测试使用 RobolectricTestRunner
kotlin
// WRONG
@RunWith(RobolectricTestRunner::class)
@Config(minSdk = 23)
class LoginViewModelTest {
@Test fun loginFlow() { /* ... */ }
}
// WRONG because: this class CAN run unchanged on a device too — there are no
// Robolectric-only APIs in the body. Pinning to RobolectricTestRunner locks the
// test to the JVM and forfeits the sharedTest pattern. The same class moved to
// src/androidTest/ (or androidDeviceTest) would not run.kotlin
// RIGHT
@RunWith(AndroidJUnit4::class)
@Config(minSdk = RobolectricMinSdk) // pin via single source of truth
class LoginViewModelTest {
@Test fun loginFlow() { /* ... */ }
}kotlin
// WRONG
@RunWith(RobolectricTestRunner::class)
@Config(minSdk = 23)
class LoginViewModelTest {
@Test fun loginFlow() { /* ... */ }
}
// WRONG because: this class CAN run unchanged on a device too — there are no
// Robolectric-only APIs in the body. Pinning to RobolectricTestRunner locks the
// test to the JVM and forfeits the sharedTest pattern. The same class moved to
// src/androidTest/ (or androidDeviceTest) would not run.kotlin
// RIGHT
@RunWith(AndroidJUnit4::class)
@Config(minSdk = RobolectricMinSdk) // pin via single source of truth
class LoginViewModelTest {
@Test fun loginFlow() { /* ... */ }
}Pattern: WRONG — assert before draining the looper
模式:错误——在清空 Looper 之前断言
kotlin
// WRONG
@RunWith(AndroidJUnit4::class)
class HandlerTest {
@Test fun postedRuns() {
var fired = false
Handler(Looper.getMainLooper()).post { fired = true }
assertTrue(fired) // FAIL: runnable is queued, not run
}
}
// WRONG because: Robolectric's default LooperMode.PAUSED does not auto-run posted
// runnables. The post is queued; assertTrue runs before the queue is drained.kotlin
// RIGHT
@RunWith(AndroidJUnit4::class)
class HandlerTest {
@Test fun postedRuns() {
var fired = false
Handler(Looper.getMainLooper()).post { fired = true }
shadowOf(Looper.getMainLooper()).idle() // drain queue
assertTrue(fired)
}
}kotlin
// WRONG
@RunWith(AndroidJUnit4::class)
class HandlerTest {
@Test fun postedRuns() {
var fired = false
Handler(Looper.getMainLooper()).post { fired = true }
assertTrue(fired) // FAIL: runnable is queued, not run
}
}
// WRONG because: Robolectric's default LooperMode.PAUSED does not auto-run posted
// runnables. The post is queued; assertTrue runs before the queue is drained.kotlin
// RIGHT
@RunWith(AndroidJUnit4::class)
class HandlerTest {
@Test fun postedRuns() {
var fired = false
Handler(Looper.getMainLooper()).post { fired = true }
shadowOf(Looper.getMainLooper()).idle() // drain queue
assertTrue(fired)
}
}Pattern: WRONG — missing includeAndroidResources
模式:错误——缺少 includeAndroidResources
gradle
// WRONG
android {
testOptions {
unitTests { /* includeAndroidResources missing */ }
}
}Symptom: at test startup. The fix:
android.content.res.Resources$NotFoundException: String resource ID #0x7f0c0001gradle
// RIGHT
android {
testOptions {
unitTests {
includeAndroidResources = true // Groovy
// isIncludeAndroidResources = true // Kotlin DSL
}
}
}gradle
// WRONG
android {
testOptions {
unitTests { /* includeAndroidResources missing */ }
}
}症状:测试启动时出现 。修复方式:
android.content.res.Resources$NotFoundException: String resource ID #0x7f0c0001gradle
// RIGHT
android {
testOptions {
unitTests {
includeAndroidResources = true // Groovy
// isIncludeAndroidResources = true // Kotlin DSL
}
}
}Pattern: WRONG — sharedTest srcDir sharing on AGP 7.2+
模式:错误——在 AGP 7.2+ 上共享 sharedTest srcDir
gradle
// WRONG
android {
sourceSets {
test { java.srcDirs += 'src/sharedTest/java' }
androidTest { java.srcDirs += 'src/sharedTest/java' }
}
}
// WRONG because: AGP 7.2+ rejects sharing a single source directory across
// source sets (Robolectric issue #7432). Build fails with "Source directory
// already added to source set".gradle
// RIGHT — AndroidX-style KMP source sets
sourceSets {
androidCommonTest { dependsOn(commonTest) }
androidDeviceTest { dependsOn(androidCommonTest) }
androidHostTest { dependsOn(androidCommonTest) }
}gradle
// WRONG
android {
sourceSets {
test { java.srcDirs += 'src/sharedTest/java' }
androidTest { java.srcDirs += 'src/sharedTest/java' }
}
}
// WRONG because: AGP 7.2+ rejects sharing a single source directory across
// source sets (Robolectric issue #7432). Build fails with "Source directory
// already added to source set".gradle
// RIGHT — AndroidX-style KMP source sets
sourceSets {
androidCommonTest { dependsOn(commonTest) }
androidDeviceTest { dependsOn(androidCommonTest) }
androidHostTest { dependsOn(androidCommonTest) }
}Pattern: ParameterizedRobolectricTestRunner — when matrix is the point
模式:ParameterizedRobolectricTestRunner——当测试矩阵本身是重点时
kotlin
// androidx/compose/ui/ui-test/.../ViewVisibilityRobolectricTest.kt (paraphrased)
@RunWith(ParameterizedRobolectricTestRunner::class)
@Config(minSdk = RobolectricMinSdk)
class ViewVisibilityRobolectricTest(private val visibility: Int) {
companion object {
@JvmStatic
@Parameters(name = "visibility={0}")
fun params() = listOf(View.VISIBLE, View.INVISIBLE, View.GONE)
}
@Test fun behaves() { /* uses `visibility` */ }
}This is the one place to pin (its parameterized subclass) — there is no parameterized variant.
RobolectricTestRunnerAndroidJUnit4kotlin
// androidx/compose/ui/ui-test/.../ViewVisibilityRobolectricTest.kt (paraphrased)
@RunWith(ParameterizedRobolectricTestRunner::class)
@Config(minSdk = RobolectricMinSdk)
class ViewVisibilityRobolectricTest(private val visibility: Int) {
companion object {
@JvmStatic
@Parameters(name = "visibility={0}")
fun params() = listOf(View.VISIBLE, View.INVISIBLE, View.GONE)
}
@Test fun behaves() { /* uses `visibility` */ }
}这是应当固定使用 (其参数化子类)的场景之一——因为不存在 的参数化变体。
RobolectricTestRunnerAndroidJUnit4Pattern: production code branching on Robolectric — read with caution
模式:生产代码根据 Robolectric 进行分支判断——谨慎使用
kotlin
// androidx/compose/ui/ui-test/.../RobolectricIdlingStrategy.android.kt
internal val HasRobolectricFingerprint
get() = Build.FINGERPRINT.lowercase() == "robolectric"This idiom is widespread inside androidx (Compose accessibility, idling, graphics layers). Library code under test SHOULD avoid copying it unless the branch is genuinely test-only — misdetection silently changes behavior.
kotlin
// androidx/compose/ui/ui-test/.../RobolectricIdlingStrategy.android.kt
internal val HasRobolectricFingerprint
get() = Build.FINGERPRINT.lowercase() == "robolectric"这种写法在 androidx 内部广泛使用(Compose 无障碍、idle 管理、图形层等)。除非该分支确实仅用于测试,否则被测库代码不应照搬这种写法——错误检测会悄无声息地改变行为。
Mandatory rules
强制规则
- MUST import from
AndroidJUnit4. MUST NOT import fromandroidx.test.ext.junit.runners— that one isandroidx.test.runner(@Deprecated§G.2).docs/CORPUS.md - MUST prefer over
@RunWith(AndroidJUnit4::class). The latter only when the test uses Robolectric-specific APIs (e.g.@RunWith(RobolectricTestRunner::class)) directly, or needsshadowOf(Looper.getMainLooper()).idle().ParameterizedRobolectricTestRunner - MUST set for any project whose unit tests touch
testOptions.unitTests.includeAndroidResources = true/R.*/ layouts / themes.Resources - MUST drain the looper with (or
shadowOf(Looper.getMainLooper()).idle()) before asserting anything that depends on aShadowLooper.runUiThreadTasksIncludingDelayedTasks()callback. DefaultHandler.post*does NOT auto-run.LooperMode.PAUSED - MUST pin a class-level (or
@Config(minSdk = …)) — do not depend on the project's default SDK varying in CI.sdk = […] - MUST NOT use the legacy sharing pattern
srcDirson AGP 7.2+. Migrate totest.java.srcDirs += 'src/sharedTest/java'+androidHostTest(KMP source sets) or a separate Gradle module.androidDeviceTest - MUST NOT add Robolectric to a test class that has zero imports. The class-load tax is 1-3 s for nothing.
android.* - MUST NOT use Robolectric for screenshot tests, ripple animations, accessibility services, or timing — use an emulator/device.
RenderThread - PREFERRED: quote from
RobolectricMinSdk = 23as the single source of truth for the floor SDK inandroidx/compose/ui/ui-test/src/androidHostTest/.../Constants.ktmodules.androidHostTest - PREFERRED: group related tests into the same class to amortize the per-class class-load tax. Avoid sprinkling across many small classes.
@RunWith(RobolectricTestRunner::class) - PREFERRED: single-SDK on the commit gate; multi-SDK matrices on the merge gate.
@Config(sdk = [33])
- 必须从 导入
androidx.test.ext.junit.runners。禁止从AndroidJUnit4导入——后者已标记为androidx.test.runner(@Deprecated§G.2)。docs/CORPUS.md - 必须优先使用 ,而不是
@RunWith(AndroidJUnit4::class)。仅当测试直接使用 Robolectric 专属 API(如@RunWith(RobolectricTestRunner::class)),或需要shadowOf(Looper.getMainLooper()).idle()时,才使用后者。ParameterizedRobolectricTestRunner - 必须为任何访问 /
R.*/ 布局 / 主题的单元测试项目设置Resources。testOptions.unitTests.includeAndroidResources = true - 必须在断言任何依赖 回调的结果之前,使用
Handler.post*(或shadowOf(Looper.getMainLooper()).idle())清空 Looper。默认的ShadowLooper.runUiThreadTasksIncludingDelayedTasks()不会自动执行任务。LooperMode.PAUSED - 必须固定类级别的 (或
@Config(minSdk = …))——不要依赖项目中可能随 CI 环境变化的默认 SDK。sdk = […] - 禁止在 AGP 7.2+ 上使用传统的 共享模式
srcDirs。请迁移到test.java.srcDirs += 'src/sharedTest/java'+androidHostTest(KMP source set)或使用独立的 Gradle module。androidDeviceTest - 禁止对没有任何 导入的测试类使用 Robolectric。否则只会白白增加 1-3 秒的类加载开销。
android.* - 禁止使用 Robolectric 测试截图、ripple 动画、无障碍服务或 时序——请使用模拟器或设备。
RenderThread - 推荐:在 module 中,将
androidHostTest中的androidx/compose/ui/ui-test/src/androidHostTest/.../Constants.kt作为最低 SDK 的单一事实来源引用。RobolectricMinSdk = 23 - 推荐:将相关测试归入同一个类,以摊薄按类加载的开销。避免在许多小类中随意添加 。
@RunWith(RobolectricTestRunner::class) - 推荐:提交门禁使用单 SDK 的 ;合并门禁使用多 SDK 矩阵。
@Config(sdk = [33])
Verification
验证
- No import of (use
androidx.test.runner.AndroidJUnit4).androidx.test.ext.junit.runners.AndroidJUnit4returns empty.grep -rn 'androidx.test.runner.AndroidJUnit4' src/test src/androidTest - is set in the module's
testOptions.unitTests.includeAndroidResources = true.build.gradle(.kts) - No exists on a test class that does not actually use Robolectric-specific APIs.
@RunWith(RobolectricTestRunner::class) - Every test that posts to a / triggers
Handlerwork callsLooper(orshadowOf(Looper.getMainLooper()).idle()) before asserting.runUiThreadTasksIncludingDelayedTasks - Every Robolectric test class declares or
@Config(minSdk = …).@Config(sdk = […]) - Source-set wiring uses +
androidHostTest(or a shared module), not legacyandroidDeviceTest.srcDirs += sharedTest - No screenshot/ripple/accessibility-service test runs under Robolectric — those live in or
src/androidTest/.androidDeviceTest - passes;
./gradlew :module:testpasses for any test in./gradlew :module:connectedDebugAndroidTest.androidCommonTest
- 没有导入 (应使用
androidx.test.runner.AndroidJUnit4)。androidx.test.ext.junit.runners.AndroidJUnit4的结果为空。grep -rn 'androidx.test.runner.AndroidJUnit4' src/test src/androidTest - 已在 module 的 中设置
build.gradle(.kts)。testOptions.unitTests.includeAndroidResources = true - 没有在实际未使用 Robolectric 专属 API 的测试类上使用 。
@RunWith(RobolectricTestRunner::class) - 每个向 发布任务或触发
Handler工作的测试,都会在断言前调用Looper(或shadowOf(Looper.getMainLooper()).idle())。runUiThreadTasksIncludingDelayedTasks - 每个 Robolectric 测试类都声明了 或
@Config(minSdk = …)。@Config(sdk = […]) - Source set 使用 +
androidHostTest(或共享 module),而不是传统的androidDeviceTest。srcDirs += sharedTest - 没有截图、ripple 或无障碍服务测试在 Robolectric 下运行——这些测试位于 或
src/androidTest/。androidDeviceTest - 通过;对于
./gradlew :module:test中的任何测试,androidCommonTest也通过。./gradlew :module:connectedDebugAndroidTest
References
参考资料
- Robolectric — getting started: http://robolectric.org/getting-started/
- Robolectric — configuring: http://robolectric.org/configuring/
- Robolectric — sharedTest blog post: http://robolectric.org/blog/2021/10/06/sharedTest/
- Android Developers — Build local unit tests: https://developer.android.com/training/testing/local-tests
- Android Developers — Robolectric: https://developer.android.com/training/testing/local-tests/robolectric
- Robolectric GitHub issue #7432 — AGP 7.2 sharedTest breakage: https://github.com/robolectric/robolectric/issues/7432
- Research: .
tasks/research/R7-robolectric.md - §G.1 / §G.6 — Gradle coordinates and runner choice.
docs/CORPUS.md - —
androidx/compose/ui/ui-test/src/androidHostTest/.../Constants.ktfloor.RobolectricMinSdk = 23 - — canonical
androidx/compose/ui/ui-test/.../RobolectricComposeTest.ktcross-runtime test.@RunWith(AndroidJUnit4::class) @Config(minSdk = RobolectricMinSdk) - —
androidx/compose/ui/ui-test/.../PrefetchNotHangingMainThreadTest.ktwith explicit@RunWith(RobolectricTestRunner::class).shadowOf(Looper.getMainLooper()).idle() - —
androidx/compose/ui/ui-test/.../ViewVisibilityRobolectricTest.ktexample.ParameterizedRobolectricTestRunner - —
androidx/compose/ui/ui-test/.../RobolectricIdlingStrategy.android.ktdetection idiom.Build.FINGERPRINT.lowercase() == "robolectric" - —
androidx/compose/ui/ui/.../MediaQueryIntegrationTest.kt/ShadowPackageManagerin anShadowInputManagertest.@RunWith(AndroidJUnit4::class) - Sibling: —
../../coroutines/testing-coroutines-with-runtest/SKILL.md+runTest(independent of Robolectric).MainDispatcherRule - Sibling: — Flow assertions; Turbine works under Robolectric unchanged.
../../coroutines/testing-flows-with-turbine/SKILL.md - Sibling: — JUnit4 plumbing surrounding Robolectric.
../../runner/configuring-junit4-on-android/SKILL.md - Sibling: — mocking Android types under Robolectric.
../../mocking/mocking-with-mockito/SKILL.md - Sibling: —
../../mocking/mocking-with-mockk/SKILL.mdfor fingerprint branches.mockkStatic(Build::class) - Cross-set: — Robolectric is "medium" tests in Google's three-size framing.
../../../fundamentals/strategies/applying-testing-strategies/SKILL.md - Cross-set: —
../../../fundamentals/strategies/organizing-test-source-sets/SKILL.mdvssrc/test/vssrc/androidTest//androidHostTest.androidDeviceTest - Cross-set: — Compose's
../../../compose/synchronization/controlling-the-test-clock/SKILL.mdis separate fromMainTestClock.ShadowLooper - Cross-set: — when the same test source needs to run on a device.
../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md
- Robolectric——入门: http://robolectric.org/getting-started/
- Robolectric——配置: http://robolectric.org/configuring/
- Robolectric——sharedTest 博客文章: http://robolectric.org/blog/2021/10/06/sharedTest/
- Android Developers——构建本地单元测试: https://developer.android.com/training/testing/local-tests
- Android Developers——Robolectric: https://developer.android.com/training/testing/local-tests/robolectric
- Robolectric GitHub issue #7432——AGP 7.2 sharedTest 失效: https://github.com/robolectric/robolectric/issues/7432
- 研究:。
tasks/research/R7-robolectric.md - §G.1 / §G.6——Gradle 坐标与运行器选择。
docs/CORPUS.md - ——
androidx/compose/ui/ui-test/src/androidHostTest/.../Constants.kt下限。RobolectricMinSdk = 23 - ——规范的
androidx/compose/ui/ui-test/.../RobolectricComposeTest.kt跨运行时测试。@RunWith(AndroidJUnit4::class) @Config(minSdk = RobolectricMinSdk) - ——使用
androidx/compose/ui/ui-test/.../PrefetchNotHangingMainThreadTest.kt并显式调用@RunWith(RobolectricTestRunner::class)。shadowOf(Looper.getMainLooper()).idle() - ——
androidx/compose/ui/ui-test/.../ViewVisibilityRobolectricTest.kt示例。ParameterizedRobolectricTestRunner - ——
androidx/compose/ui/ui-test/.../RobolectricIdlingStrategy.android.kt检测方式。Build.FINGERPRINT.lowercase() == "robolectric" - ——在
androidx/compose/ui/ui/.../MediaQueryIntegrationTest.kt测试中使用@RunWith(AndroidJUnit4::class)/ShadowPackageManager。ShadowInputManager - 同级:——
../../coroutines/testing-coroutines-with-runtest/SKILL.md+runTest(独立于 Robolectric)。MainDispatcherRule - 同级:——Flow 断言;Turbine 在 Robolectric 下无需改动即可使用。
../../coroutines/testing-flows-with-turbine/SKILL.md - 同级:——Robolectric 周围的 JUnit4 配置。
../../runner/configuring-junit4-on-android/SKILL.md - 同级:——在 Robolectric 下 mock Android 类型。
../../mocking/mocking-with-mockito/SKILL.md - 同级:——对 fingerprint 分支使用
../../mocking/mocking-with-mockk/SKILL.md。mockkStatic(Build::class) - 跨集合:——在 Google 的三档测试框架中,Robolectric 属于“中等”测试。
../../../fundamentals/strategies/applying-testing-strategies/SKILL.md - 跨集合:——
../../../fundamentals/strategies/organizing-test-source-sets/SKILL.md、src/test/、src/androidTest//androidHostTest之间的区别。androidDeviceTest - 跨集合:——Compose 的
../../../compose/synchronization/controlling-the-test-clock/SKILL.md与MainTestClock相互独立。ShadowLooper - 跨集合:——当相同测试源需要在设备上运行时使用。
../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md