Android unit and instrumentation testing gotchas
androidtestingjunitmockkrobolectriccoroutinescomposehiltgradle
Collected traps from a Kotlin/Compose app with more than 1,300 JVM unit tests (JUnit 4, MockK, Robolectric, kotlinx-coroutines-test) and a few instrumentation tests. Many of them make tests pass while testing nothing, which is worse than failing.
Coroutines
advanceUntilIdle()does not advance virtual time forbackgroundScopedelays. A debounce launched inTestScope.backgroundScopenever fires; two tests silently asserted against coroutines that never ran. UseadvanceTimeBy(ms)thenrunCurrent().- Tickers that mix virtual
delay(1000)withSystem.currentTimeMillis(): userunCurrent()to see the first tick,advanceUntilIdle()to drain. - Catch-all error helpers must rethrow
CancellationException.
MockK
mockkStatic(System::class)plus stubbingcurrentTimeMillis()causes a StackOverflowError, since MockK uses that call internally. Inject a clock instead.- Capturing arguments in
coEveryraces when the call lands on aDispatchers.IOworker (plain ArrayList, no happens-before). Capture insidecoVerify(timeout = ...); MockK's call store is synchronized.
Robolectric
PhoneNumberUtils.formatNumberToE164may or may not return null depending on version (it worked on Robolectric 4.14 / SDK 33 for valid US numbers). Assert contracts (\+?\d+), not exact strings.Telephony.Threads.getOrCreateThreadIdthrowsAbstractMethodError; such tests need a device.- There is no AndroidKeyStore; code that unwraps keys must tolerate that or be faked.
Hilt
@AndroidEntryPointBroadcastReceivers cannot be spied or subclassed in unit tests (Hilt generates a final subclass). Test them on a device.- API 35 emulators redeliver a deferred
BOOT_COMPLETEDon every process start, so a Hilt-injected BootReceiver crashesHiltTestApplicationbeforeHiltAndroidRuleruns ("The component was not created"). Before Hilt instrumentation runs:adb shell pm disable-user --user 0 <pkg>/<BootReceiver>, check its output, and launch the app once to consume the broadcast.
Compose and Kotlin compile traps
AnimatedVisibilityinside aLazyColumnitem that is lexically inside aColumnresolves to theColumnScopeextension and fails to compile. An import alias does not help (same FQN); hoist into a top-level private composable.- There is no
Spring.StiffnessMediumHigh; use a literal (about 2800f). - A
suspendcall insidejoinToString { }does not compile (the transform is a nullable function type, not inlined). Use.map { }.joinToString().
Build and tooling
./gradlew test | tailreports tail's exit code. CheckPIPESTATUSor redirect to a file and echo$?.- A full-suite run sometimes exits 134 (SIGABRT/SIGSEGV) with every test passing: a host OpenJDK 17 C2 JIT bug (
Node::uncastwhile compiling Room'sbeginTransaction,hs_err_pid*.login the module). Read the test-results XML; if failures are 0, rerun. androidTestsources are not compiled byassembleReleaseor the unit suite, so they rot silently. Compile them periodically (:app:compileDebugAndroidTestKotlin). Migration device tests also go stale when the schema moves on: a test that builds Room with only the migrations up to v17 fails with "A migration from 16 to 18 was required" once the schema is v18. Checking out oldapp/srcalso reverts them to versions that may never have compiled.- A C1-only test JVM can hang the whole suite.
-XX:TieredStopAtLevel=1(a common speed-up for unit tests) defaults to a 48 MB code cache. A 1,400-test suite filled it ("CodeCache is full. Compiler has been disabled"), and the Gradle test executor then sat idle for 80+ minutes with no test running. Add-XX:ReservedCodeCacheSize=256mto the testjvmArgs. - Only the debug unit-test variant may have Room schema assets; stale release-variant results can show false migration failures.