Testing Coroutines & Flow Interview Questions

TESTING › Unit

How do you test a suspend function?

What a strong answer covers: Use runTest from kotlinx-coroutines-test, which runs the test in a TestScope with virtual time, so delay() skips instantly. Call the suspend function directly inside runTest and assert on the result. It also fails the test if coroutines launched inside it are still running at the end.

Why do you need to replace Dispatchers.Main in unit tests, and how?

What a strong answer covers: Dispatchers.Main needs the Android main Looper, which doesn't exist in local JVM tests, so code using viewModelScope fails. Call Dispatchers.setMain(testDispatcher) before each test and resetMain() after, usually in a JUnit rule (MainDispatcherRule). Share the same scheduler with runTest so virtual time is consistent.

What's the difference between StandardTestDispatcher and UnconfinedTestDispatcher?

What a strong answer covers: StandardTestDispatcher queues new coroutines and only runs them when you advance the scheduler (advanceUntilIdle, runCurrent) or the test suspends, which gives precise control over ordering. UnconfinedTestDispatcher starts new coroutines eagerly, which is convenient for collectors that need to be running before you emit, but hides ordering issues.

How do you test a Flow, including StateFlow, and what does Turbine add?

What a strong answer covers: For a finite flow, toList() or first(). For a StateFlow in a ViewModel, either check uiState.value after advancing, or collect it in backgroundScope so intermediate states are captured. Turbine's flow.test { assertEquals(Loading, awaitItem()); assertEquals(Success, awaitItem()) } gives sequential assertions, timeouts and errors when unexpected events remain. With stateIn(WhileSubscribed), there must be an active collector or nothing upstream runs.

How do you make coroutine code testable when it hard-codes Dispatchers.IO, and how do you test timing behaviour like debounce or retry with backoff?

What a strong answer covers: Inject dispatchers (a constructor parameter or DispatcherProvider) so tests pass the test dispatcher; hard-coded IO runs on real threads and escapes virtual time, causing flaky tests. With everything on the test scheduler, debounce and backoff delays are virtual: advanceTimeBy(299) and assert nothing happened, then advanceTimeBy(1) and assert the search ran; for retry, a fake that fails twice, then check attempts and currentTime.

Back to Testing Coroutines & Flow