Testing basics cheat sheet
Key ideas
- Local unit tests live in
src/test(JVM, fast); instrumented tests live insrc/androidTest(device or emulator, slower). - JUnit 4 is the Android default; use
@Test,@Before,@After— JUnit 5 annotations like@BeforeEachdo nothing in a JUnit 4 run. coEveryandcoVerifystub and verifysuspendfunctions; calling asuspendfunction insideeveryorverifydoes not compile.runTestreplacesrunBlockingin tests: it skipsdelaywith virtual time and waits for child coroutines before finishing.StandardTestDispatcheris the default insiderunTest; new coroutines stay queued until you callrunCurrent()oradvanceUntilIdle().Dispatchers.setMain/resetMainmust live in a JUnit rule (@get:Rule) so cleanup runs even when an assertion fails.- Prefer hand-written fakes for stateful dependencies (cache, repository); reserve MockK for interaction checks like call counts.
- Compose UI tests use
@get:RulewithcreateComposeRule(); finders search the merged semantics tree by default. - Turbine's
test { }block fails if events are left unconsumed; callcancelAndIgnoreRemainingEvents()when the rest does not matter. mockkObject/mockkStaticchange global state; undo withunmockkAll()in@Afteror the mock leaks into later tests.
APIs at a glance
| API or term | Use it for |
|---|---|
@Test / @Before / @After | JUnit 4 lifecycle annotations; the Android default test framework. |
coEvery / coVerify | Stub and verify suspend functions in MockK; every / verify blocks cannot call suspend functions. |
runTest | Test scope that skips delay with virtual time and waits for child coroutines; replaces runBlocking in tests. |
StandardTestDispatcher | Default dispatcher inside runTest; queues coroutines until runCurrent() or advanceUntilIdle() is called. |
Dispatchers.setMain / Dispatchers.resetMain | Replace the Main dispatcher for JVM tests; wrap in a @get:Rule so cleanup always runs. |
slot<T>() / capture | Capture the argument a mock received inside a stub, then assert on it after the call. |
confirmVerified | Fail the test if the mock received any call that no verify block covered. |
createComposeRule | JUnit rule that hosts Compose content via setContent; use createAndroidComposeRule for a real activity. |
onNodeWithText / onNodeWithTag | Compose 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 / performTextReplacement | Type 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
runTestoverrunBlockingin tests; it skipsdelaywith 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/resetMainby hand; use a@get:Ruleso cleanup runs even when an assertion fails. - Prefer
testTagover text finders in Compose tests; text changes with language or copy edits. - Never leave
mockkObjectormockkStaticwithoutunmockkAll()in@After; the mock leaks into later tests in the same JVM.
Gotchas
- Using every on a suspend function. The
everyblock is not a suspend lambda, so the call does not compile. UsecoEveryandcoVerifyfor allsuspendfunctions. - Forgetting advanceUntilIdle() with StandardTestDispatcher. The launched coroutine stays queued, the state stays
Loading, and the assertion fails. CalladvanceUntilIdle()orrunCurrent()before asserting the final state. - Putting an assertion inside waitUntil. The lambda must return
Boolean; a thrown assertion is not retried. Check a condition likefetchSemanticsNodes().isNotEmpty()or usewaitUntilExactlyOneExists. - Using performTextInput expecting it to replace text. It types at the cursor, so the old text stays. Use
performTextReplacementorperformTextClearancefirst. - 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
backgroundScopebefore 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.