Testing basics cheat sheet

Revise Android testing: JUnit 4, MockK, runTest, Turbine, Compose UI tests, ViewModel testing, StandardTestDispatcher, and Dispatchers.setMain.

Key ideas

  1. Local unit tests live in src/test (JVM, fast); instrumented tests live in src/androidTest (device or emulator, slower).
  2. JUnit 4 is the Android default; use @Test, @Before, @After — JUnit 5 annotations like @BeforeEach do nothing in a JUnit 4 run.
  3. coEvery and coVerify stub and verify suspend functions; calling a suspend function inside every or verify does not compile.
  4. runTest replaces runBlocking in tests: it skips delay with virtual time and waits for child coroutines before finishing.
  5. StandardTestDispatcher is the default inside runTest; new coroutines stay queued until you call runCurrent() or advanceUntilIdle().
  6. Dispatchers.setMain / resetMain must live in a JUnit rule (@get:Rule) so cleanup runs even when an assertion fails.
  7. Prefer hand-written fakes for stateful dependencies (cache, repository); reserve MockK for interaction checks like call counts.
  8. Compose UI tests use @get:Rule with createComposeRule(); finders search the merged semantics tree by default.
  9. Turbine's test { } block fails if events are left unconsumed; call cancelAndIgnoreRemainingEvents() when the rest does not matter.
  10. mockkObject / mockkStatic change global state; undo with unmockkAll() in @After or the mock leaks into later tests.

APIs at a glance

API or termUse it for
@Test / @Before / @AfterJUnit 4 lifecycle annotations; the Android default test framework.
coEvery / coVerifyStub and verify suspend functions in MockK; every / verify blocks cannot call suspend functions.
runTestTest scope that skips delay with virtual time and waits for child coroutines; replaces runBlocking in tests.
StandardTestDispatcherDefault dispatcher inside runTest; queues coroutines until runCurrent() or advanceUntilIdle() is called.
Dispatchers.setMain / Dispatchers.resetMainReplace the Main dispatcher for JVM tests; wrap in a @get:Rule so cleanup always runs.
slot<T>() / captureCapture the argument a mock received inside a stub, then assert on it after the call.
confirmVerifiedFail the test if the mock received any call that no verify block covered.
createComposeRuleJUnit rule that hosts Compose content via setContent; use createAndroidComposeRule for a real activity.
onNodeWithText / onNodeWithTagCompose test finders on the semantics tree; fail if zero or more than one node matches.
Turbine test { } / awaitItem()Collect and assert on Flow emissions; unconsumed events at block end fail the test.
performTextInput / performTextReplacementType at the cursor or replace existing text in a Compose TextField.
unmockkAll()Undo mockkObject / mockkStatic in @After to prevent global mock leakage.

Snippets

MockK coEvery with slot capture

data class User(val name: String)
interface UserRepository { suspend fun fetchUser(id: String): User? }
class GetUserName(private val repository: UserRepository) {
    suspend operator fun invoke(rawId: String): String =
        repository.fetchUser(rawId.trim())?.name ?: "Unknown"
}
 
@Test
fun trimsIdAndFallsBackToUnknown() = runTest {
    val repository = mockk<UserRepository>()
    val idSlot = slot<String>()
    coEvery { repository.fetchUser(capture(idSlot)) } returns null
 
    val name = GetUserName(repository)("  99 ")
 
    assertEquals("99", idSlot.captured)
    assertEquals("Unknown", name)
}

ViewModel test with a Main dispatcher rule

class MainDispatcherRule(
    private val dispatcher: TestDispatcher = StandardTestDispatcher(),
) : TestWatcher() {
    override fun starting(description: Description) = Dispatchers.setMain(dispatcher)
    override fun finished(description: Description) = Dispatchers.resetMain()
}
 
// UserViewModel, FakeUserRepository and UiState are the app code under test
class UserViewModelTest {
    @get:Rule val mainDispatcherRule = MainDispatcherRule()
 
    @Test
    fun loadUser_showsSuccess() = runTest {
        val vm = UserViewModel(FakeUserRepository())
 
        vm.loadUser(1)
        advanceUntilIdle()
 
        assertEquals(UiState.Success("Alice"), vm.uiState.value)
    }
}

Compose UI test with createComposeRule

// LoginForm is the composable under test
class LoginFormTest {
    @get:Rule val rule = createComposeRule()
 
    @Test
    fun blankEmail_showsError() {
        rule.setContent { LoginForm() }
        rule.onNodeWithText("Sign in").performClick()
        rule.onNodeWithTag("error_text")
            .assertIsDisplayed()
            .assertTextEquals("Email is required")
    }
}

Rules of thumb

  • Prefer runTest over runBlocking in tests; it skips delay with virtual time and fails cleanly on uncaught exceptions.
  • Prefer hand-written fakes for stateful dependencies; reserve MockK for interaction checks like call counts.
  • Never share mocks through a companion object; JUnit 4 creates a new class instance per test, so keep mocks in normal fields.
  • Never call Dispatchers.setMain / resetMain by hand; use a @get:Rule so cleanup runs even when an assertion fails.
  • Prefer testTag over text finders in Compose tests; text changes with language or copy edits.
  • Never leave mockkObject or mockkStatic without unmockkAll() in @After; the mock leaks into later tests in the same JVM.

Gotchas

  • Using every on a suspend function. The every block is not a suspend lambda, so the call does not compile. Use coEvery and coVerify for all suspend functions.
  • Forgetting advanceUntilIdle() with StandardTestDispatcher. The launched coroutine stays queued, the state stays Loading, and the assertion fails. Call advanceUntilIdle() or runCurrent() before asserting the final state.
  • Putting an assertion inside waitUntil. The lambda must return Boolean; a thrown assertion is not retried. Check a condition like fetchSemanticsNodes().isNotEmpty() or use waitUntilExactlyOneExists.
  • Using performTextInput expecting it to replace text. It types at the cursor, so the old text stays. Use performTextReplacement or performTextClearance first.
  • Reading .value of a stateIn(WhileSubscribed) flow without a collector. It never leaves the initial value because no active subscriber exists. Collect with Turbine or backgroundScope before reading.
  • Using @Rule instead of @get:Rule in Kotlin. JUnit needs the annotation on the getter; on the field it fails with "The @Rule 'rule' must be public". Use @get:Rule.

Quick interview answers

Why does every { repo.fetchUser("1") } fail to compile when fetchUser is a suspend function?

The every block is not a suspend lambda, so calling a suspend function inside it is a compile error. Use coEvery and coVerify for all suspend functions.

What is the difference between src/test and src/androidTest?

src/test holds local unit tests that run on the JVM without the Android runtime, so they are fast. src/androidTest holds instrumented tests that run on a device or emulator and can touch Android framework classes.

Why must Dispatchers.setMain and resetMain live in a JUnit rule?

If an assertion fails before resetMain runs, the replaced Main dispatcher leaks into later tests in the same JVM, causing order-dependent failures. A @get:Rule guarantees cleanup even when the test throws.

When should you use a hand-written fake instead of MockK?

When the dependency holds state, such as a cache, session, or repository, a small fake with a MutableMap or list is easier to read and less brittle. Reserve MockK for checking interactions like call counts.

Why does a Compose UI test fail with "The @Rule 'rule' must be public"?

In Kotlin, @Rule on a field does not put the annotation on the getter, which is what JUnit needs. Use @get:Rule so the annotation lands on the getter.

What happens if you leave events unconsumed in a Turbine test { } block?

Turbine fails the test at the end of the block because it detects remaining events. Either await every event with awaitItem() / awaitError(), or call cancelAndIgnoreRemainingEvents() when the rest does not matter.

Go deeper