Loading...
Loading...
Use this skill to run Android-aware unit tests on the JVM with Robolectric — the right runner choice (AndroidJUnit4 vs RobolectricTestRunner), @Config sdk/qualifiers/application, the includeAndroidResources requirement, common shadows (ShadowApplication, ShadowLog, ShadowLooper, ShadowPackageManager, ShadowSystemClock), looper draining (shadowOf(Looper.getMainLooper()).idle()), and when NOT to reach for Robolectric (screenshot tests, RenderThread, accessibility services). Also covers the AGP 7.2+ sharedTest reality check and the migration to KMP androidHostTest/androidDeviceTest. If the user mentions Robolectric, AndroidJUnit4 host test, RobolectricTestRunner, @Config, includeAndroidResources, ShadowLooper.idle, shadowOf, sharedTest broken on AGP 7.2, ParameterizedRobolectricTestRunner, "test passes on JVM fails on device", or "Resources NotFoundException" in unit tests, use this skill.
npx skill4agent add skydoves/android-testing-skills using-robolectric-correctlyRenderThread@Config../../../compose/synchronization/controlling-the-test-clock/SKILL.mdandroid.*RuntimeException: Method ... not mockedResources$NotFoundExceptiontestOptions.unitTests.includeAndroidResourcesHandler.postDelayedLooperLooperMode.PAUSEDsharedTestandroidHostTestandroidDeviceTestsharedTestsrcDirandroid.*../../runner/configuring-junit4-on-android/SKILL.mdRenderThread../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.mdrunTest../../coroutines/testing-coroutines-with-runtest/SKILL.md../../../compose/setup/configuring-test-dependencies/SKILL.md../../../compose/synchronization/controlling-the-test-clock/SKILL.mdtestImplementation("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.AndroidJUnit4docs/CORPUS.mdandroid {
testOptions {
unitTests {
includeAndroidResources = true // non-negotiable
}
}
}includeAndroidResourcesR.*Resourcesres/// androidx/compose/ui/ui-test/src/androidHostTest/.../Constants.kt
internal const val RobolectricMinSdk = 23@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 |
docs/CORPUS.mdimport 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 */ }androidx.test.runner.AndroidJUnit4ext.junit.runners@Deprecateddocs/CORPUS.mdandroidx.test.ext.junit.runners@Config// 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 WithFakeAppsdkminSdkmaxSdkminSdkmaxSdk@Config(sdk = [<one SDK>])@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)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)LooperMode.PAUSEDimport 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))MainTestClock.advanceTimeBy(...)runComposeUiTest { … waitForIdle() }RobolectricIdlingStrategytestandroidTest// LEGACY — broken on AGP 7.2+
android {
sourceSets {
String dir = 'src/sharedTest/'
test { java.srcDirs += dir + 'java' }
androidTest { java.srcDirs += dir + 'java' }
}
}commonTest{androidHostTest, androidDeviceTest}androidXMultiplatformsourceSets {
androidCommonTest { dependsOn(commonTest) }
androidDeviceTest { dependsOn(androidCommonTest) } // instrumented APK
androidHostTest { dependsOn(androidCommonTest) } // Robolectric on JVM
}testandroidTesttestImplementationandroidTestImplementationandroidHostTestandroidDeviceTest@RunWith(AndroidJUnit4::class)AndroidJUnit4../../../fundamentals/strategies/organizing-test-source-sets/SKILL.md| 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. |
// 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.// RIGHT
@RunWith(AndroidJUnit4::class)
@Config(minSdk = RobolectricMinSdk) // pin via single source of truth
class LoginViewModelTest {
@Test fun loginFlow() { /* ... */ }
}// 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.// 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)
}
}// WRONG
android {
testOptions {
unitTests { /* includeAndroidResources missing */ }
}
}android.content.res.Resources$NotFoundException: String resource ID #0x7f0c0001// RIGHT
android {
testOptions {
unitTests {
includeAndroidResources = true // Groovy
// isIncludeAndroidResources = true // Kotlin DSL
}
}
}// 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".// RIGHT — AndroidX-style KMP source sets
sourceSets {
androidCommonTest { dependsOn(commonTest) }
androidDeviceTest { dependsOn(androidCommonTest) }
androidHostTest { dependsOn(androidCommonTest) }
}// 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` */ }
}RobolectricTestRunnerAndroidJUnit4// androidx/compose/ui/ui-test/.../RobolectricIdlingStrategy.android.kt
internal val HasRobolectricFingerprint
get() = Build.FINGERPRINT.lowercase() == "robolectric"AndroidJUnit4androidx.test.ext.junit.runnersandroidx.test.runner@Deprecateddocs/CORPUS.md@RunWith(AndroidJUnit4::class)@RunWith(RobolectricTestRunner::class)shadowOf(Looper.getMainLooper()).idle()ParameterizedRobolectricTestRunnertestOptions.unitTests.includeAndroidResources = trueR.*ResourcesshadowOf(Looper.getMainLooper()).idle()ShadowLooper.runUiThreadTasksIncludingDelayedTasks()Handler.post*LooperMode.PAUSED@Config(minSdk = …)sdk = […]srcDirstest.java.srcDirs += 'src/sharedTest/java'androidHostTestandroidDeviceTestandroid.*RenderThreadRobolectricMinSdk = 23androidx/compose/ui/ui-test/src/androidHostTest/.../Constants.ktandroidHostTest@RunWith(RobolectricTestRunner::class)@Config(sdk = [33])androidx.test.runner.AndroidJUnit4androidx.test.ext.junit.runners.AndroidJUnit4grep -rn 'androidx.test.runner.AndroidJUnit4' src/test src/androidTesttestOptions.unitTests.includeAndroidResources = truebuild.gradle(.kts)@RunWith(RobolectricTestRunner::class)HandlerLoopershadowOf(Looper.getMainLooper()).idle()runUiThreadTasksIncludingDelayedTasks@Config(minSdk = …)@Config(sdk = […])androidHostTestandroidDeviceTestsrcDirs += sharedTestsrc/androidTest/androidDeviceTest./gradlew :module:test./gradlew :module:connectedDebugAndroidTestandroidCommonTesttasks/research/R7-robolectric.mddocs/CORPUS.mdandroidx/compose/ui/ui-test/src/androidHostTest/.../Constants.ktRobolectricMinSdk = 23androidx/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.ktParameterizedRobolectricTestRunnerandroidx/compose/ui/ui-test/.../RobolectricIdlingStrategy.android.ktBuild.FINGERPRINT.lowercase() == "robolectric"androidx/compose/ui/ui/.../MediaQueryIntegrationTest.ktShadowPackageManagerShadowInputManager@RunWith(AndroidJUnit4::class)../../coroutines/testing-coroutines-with-runtest/SKILL.mdrunTestMainDispatcherRule../../coroutines/testing-flows-with-turbine/SKILL.md../../runner/configuring-junit4-on-android/SKILL.md../../mocking/mocking-with-mockito/SKILL.md../../mocking/mocking-with-mockk/SKILL.mdmockkStatic(Build::class)../../../fundamentals/strategies/applying-testing-strategies/SKILL.md../../../fundamentals/strategies/organizing-test-source-sets/SKILL.mdsrc/test/src/androidTest/androidHostTestandroidDeviceTest../../../compose/synchronization/controlling-the-test-clock/SKILL.mdMainTestClockShadowLooper../../../instrumentation/runner/running-instrumented-tests-with-androidjunit4/SKILL.md