/engsys-kotlin:android-testingfrom engsys-kotlin
Write and review Android/Kotlin tests across the pyramid: JUnit (4/5) unit tests, MockK, Turbine for Flow/StateFlow assertions, coroutine testing with runTest and test dispatchers, Robolectric JVM tests, Espresso instrumented UI tests, and Compose UI testing with createComposeRule and semantics matchers. Use when writing or fixing unit tests, testing coroutines/Flows, mocking dependencies, choosing JVM vs instrumented tests, or testing Compose UI and ViewModels on Android.
Ships in engsys-kotlin. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Write and review tests for Android/Kotlin targeting JUnit, MockK, Turbine, kotlinx-coroutines-test, Robolectric, Espresso, and Compose UI testing. Favor a test pyramid: many fast JVM unit tests, fewer Robolectric/Compose tests, and a thin layer of instrumented end-to-end tests. Test behavior, not implementation.
| Location | Runs on | Use for |
|---|---|---|
src/test/ | Local JVM (testDebugUnitTest) | Logic, ViewModels, repos, mappers, Robolectric |
src/androidTest/ | Device/emulator (connectedDebugAndroidTest) | Espresso, Compose UI, integration |
Keep most tests in src/test/ — they are fast and run in the unit-test gate.
Reserve src/androidTest/ for tests that genuinely need a device/emulator.
JUnit 4 is still the Android default; JUnit 5 is fine for pure-JVM modules with the platform engine configured. Name tests by behavior.
class PriceFormatterTest {
@Test
fun `formats whole dollars without decimals`() {
assertEquals("$5", PriceFormatter.format(500))
}
}
Prefer a fluent assertion library (Truth or AssertK) for readable failures:
assertThat(result).isEqualTo(expected)
assertThat(items).containsExactly(a, b).inOrder()
MockK is the idiomatic Kotlin mocking library (handles final classes, coroutines, and relaxed mocks). Prefer fakes for owned interfaces; use mocks for verifying interactions or stubbing boundaries.
@Test
fun `loads profile from repo`() = runTest {
val repo = mockk<ProfileRepository>()
coEvery { repo.profile(42) } returns Profile(name = "Ada")
val result = ProfileService(repo).load(42)
assertThat(result.name).isEqualTo("Ada")
coVerify(exactly = 1) { repo.profile(42) }
}
coEvery/coVerify for suspend functions.relaxed = true to auto-stub return values you don't care about.Use kotlinx-coroutines-test. runTest provides a TestScope with a virtual
clock that auto-advances through delay.
@Test
fun `retries after delay`() = runTest {
val result = withTimeout(1.seconds) { service.fetchWithRetry() }
assertThat(result).isNotNull()
// delay(30_000) inside fetchWithRetry is skipped — virtual time
}
MainDispatcherRule to swap Dispatchers.Main (needed for viewModelScope):class MainDispatcherRule(
private val dispatcher: TestDispatcher = StandardTestDispatcher(),
) : TestWatcher() {
override fun starting(d: Description) = Dispatchers.setMain(dispatcher)
override fun finished(d: Description) = Dispatchers.resetMain()
}
StandardTestDispatcher queues coroutines — call advanceUntilIdle() /
runCurrent() to run them. UnconfinedTestDispatcher runs eagerly — handy for
simple cases but order-sensitive.Thread.sleep or real delay waits in tests.Turbine makes Flow assertions deterministic without manual collection
boilerplate. Use it for Flow, StateFlow, and SharedFlow.
@Test
fun `emits loading then loaded`() = runTest {
viewModel.uiState.test {
assertThat(awaitItem()).isEqualTo(UiState.Loading)
viewModel.load()
assertThat(awaitItem()).isInstanceOf(UiState.Loaded::class.java)
cancelAndIgnoreRemainingEvents()
}
}
awaitItem() suspends for the next emission; awaitError() / awaitComplete()
for terminal events.StateFlow, the first awaitItem() is the current value; call
cancelAndIgnoreRemainingEvents() (or expectMostRecentItem()) to finish.test {} fails if unconsumed events remain — this catches unexpected emissions.Combine the MainDispatcherRule, runTest, fakes, and Turbine:
class FeedViewModelTest {
@get:Rule val mainDispatcherRule = MainDispatcherRule()
@Test
fun `shows error when repo throws`() = runTest {
val repo = FakeFeedRepository(throws = IOException())
val vm = FeedViewModel(repo)
vm.state.test {
assertThat(awaitItem()).isEqualTo(FeedUiState.Loading)
assertThat(awaitItem()).isInstanceOf(FeedUiState.Error::class.java)
cancelAndIgnoreRemainingEvents()
}
}
}
Robolectric runs Android-framework-dependent code on the JVM (no emulator), so
it stays in src/test/. Use it when a unit test needs Context, resources,
SharedPreferences, or Android components — but the logic doesn't need a real
device.
@RunWith(RobolectricTestRunner::class)
class ResourceTest {
@Test
fun `reads string resource`() {
val context = ApplicationProvider.getApplicationContext<Context>()
assertThat(context.getString(R.string.app_name)).isEqualTo("Demo")
}
}
Prefer pure unit tests where possible; reach for Robolectric only when framework types are genuinely involved. It is slower than plain JVM tests but far faster than instrumented ones.
Use createComposeRule() (no Activity) or createAndroidComposeRule<Activity>().
These can run as Robolectric tests in src/test/ or instrumented in
src/androidTest/. Query by semantics, and add Modifier.testTag /
content descriptions for stable selectors.
class CounterTest {
@get:Rule val composeRule = createComposeRule()
@Test
fun increments_on_click() {
composeRule.setContent { Counter() }
composeRule.onNodeWithText("Count: 0").assertIsDisplayed()
composeRule.onNodeWithTag("increment").performClick()
composeRule.onNodeWithText("Count: 1").assertExists()
}
}
composeRule.waitUntil { ... }.onNodeWithTag/onNodeWithContentDescription for robust, localized-text-
independent selectors.mainClock.autoAdvance = false to
control time when asserting animated states.Espresso drives real instrumented UI tests (src/androidTest/, runs on an
emulator/device). Use for end-to-end flows and legacy View-based screens.
@RunWith(AndroidJUnit4::class)
class LoginFlowTest {
@get:Rule val activityRule = ActivityScenarioRule(LoginActivity::class.java)
@Test
fun successful_login_navigates_home() {
onView(withId(R.id.email)).perform(typeText("[email protected]"))
onView(withId(R.id.submit)).perform(click())
onView(withId(R.id.home)).check(matches(isDisplayed()))
}
}
IdlingResource for custom async work.Thread.sleep/real delays in tests — use runTest virtual time and
Turbine/waitUntil.MainDispatcherRule when testing viewModelScope — Dispatchers.Main
isn't available on the JVM and the test fails or hangs.androidTest — slow; most tests belong in test/.testTag/content
descriptions.Dispatchers.setMain — always resetMain() (the rule handles it).cancelAndIgnore without checking.src/test/runTest; no real sleeps/delaysMainDispatcherRule present for ViewModel/viewModelScope testsawaitItem/awaitError)testTag, not localized textWhat SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub eric-sabe/engsys --plugin engsys-kotlin3 skills in this plugin
/jetpack-composeBuild Android UIs with Jetpack Compose: composition, state hoisting, remember/rememberSaveable/derivedStateOf, recomposition correctness and performance, side-effect APIs (LaunchedEffect/DisposableEffect/rememberCoroutineScope/produceState/snapshotFlow), Material 3 theming, and Compose navigation. Use when writing or reviewing @Composable functions, fixing recomposition or state bugs, hoisting state, choosing a side-effect API, applying Material 3, or improving Compose performance and stability./kotlin-coroutinesWrite data-safe asynchronous Kotlin with coroutines, Flow, and structured concurrency on Android. Use when fixing coroutine cancellation or leak bugs, choosing dispatchers (Default/IO/Main), designing suspend functions, modeling streams with Flow/StateFlow/SharedFlow, scoping work to viewModelScope/lifecycleScope, handling exceptions with CoroutineExceptionHandler/supervisorScope, or converting callback/RxJava APIs to coroutines. Covers Kotlin 2.x, kotlinx.coroutines structured concurrency discipline, and the Android main-safety contract.