using-robolectric-correctly
Installation
SKILL.md
Using Robolectric Correctly — Android On The JVM, Without The Footguns
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 RenderThread, no real Binder, no real GPU. This skill locks down the runner choice, the @Config matrix, the looper draining ritual, and the AGP 7.2+ sharedTest gotcha. Compose-on-Robolectric specifics live in ../../../compose/synchronization/controlling-the-test-clock/SKILL.md.
When to use this skill
- The class under test imports
android.*(Context, Resources, View, PackageManager, Looper) and the developer wants to test it on the JVM in seconds, not on an emulator in minutes. - A unit test fails with
RuntimeException: Method ... not mocked(the bare-Android-jar default) — the developer needs Robolectric's shadows. - A unit test fails with
Resources$NotFoundException—testOptions.unitTests.includeAndroidResourcesis missing. - The developer asks "AndroidJUnit4 vs RobolectricTestRunner — which?".
- A
Handler.postDelayed/Looperqueue does not advance under Robolectric's defaultLooperMode.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
sharedTestsrcDirsharing pattern.