ViewModel tests
Why it matters
- ViewModels hold the UI state logic; a bug there shows up on every screen that uses it, and the logic can be tested in isolation on the JVM in milliseconds.
- Interviewers at mid-to-senior level ask you to walk through a ViewModel test: fake vs mock, replacing
Dispatchers.Main, and state assertions. - A missing error-path test is a classic way for an endless loading spinner to reach production.
- A well-structured ViewModel test doubles as executable documentation of the screen's state machine, which helps onboarding and code review.
The simple explanation
- You are testing a thermostat controller, not the furnace.
- The fake temperature sensor (fake repository) returns a value you choose.
- You check that the controller sets the right mode (assert the UiState).
- You never power on the real furnace (no network, no database).
- The test runs on a workbench, not in the house (JVM, no Android runtime).
- Virtual time lets you fast-forward the clock so the test finishes in milliseconds.
A ViewModel test lives in src/test and runs on the JVM. No Android runtime, no device. The pattern has three moving parts:
-
Fake dependency. A hand-written fake repository is the site's default (see the repository pattern lesson): a small class with in-memory data that the test can set to succeed or fail. Reach for MockK when the point of the test is an interaction, such as "analytics was called once".
-
Main dispatcher.
viewModelScopeusesDispatchers.Main.immediate, andDispatchers.Maindoes not exist in a JVM test. AMainDispatcherRulecallsDispatchers.setMain(StandardTestDispatcher())before each test andDispatchers.resetMain()after it.runTestthen reuses that dispatcher's scheduler, sorunCurrent()andadvanceUntilIdle()control the ViewModel's coroutines. Dispatchers used deeper down, such as an IO dispatcher in a repository, are injected through constructors; with a fake repository the ViewModel test usually does not need them at all. -
State assertion. The ViewModel exposes a
StateFlow<UiState>. With aMutableStateFlowbehind it you can readviewModel.uiState.valueafter advancing the scheduler. If the state is built withstateIn(WhileSubscribed), it needs a collector first: Turbine'stest { }or a collector inbackgroundScope.
| Concern | Tool | Why |
|---|---|---|
| Coroutine control | runTest, runCurrent(), advanceUntilIdle() | Virtual time; no real waiting |
| Dependency | Hand-written fake | Readable, deterministic |
| Main dispatcher | MainDispatcherRule with setMain / resetMain | viewModelScope needs it |
| Assertion | assertEquals(expected, viewModel.uiState.value) | Checks the public contract, not internals |
The test follows arrange-act-assert: set up the fake, create the ViewModel, call the method, drive the scheduler, assert the state. Because StandardTestDispatcher queues the launched coroutine, you can assert Loading before advancing and Success or Error after.
Notes
- ViewModel tests go in
src/test(local, JVM). They do not need a device or Robolectric unless the ViewModel touches Android framework classes. - Use a hand-written fake repository by default. Use MockK when you need to check an interaction, like a call count.
- Without a replaced Main dispatcher,
viewModelScope.launchfails withIllegalStateException: Module with the Main dispatcher had failed to initialize(or "is missing", depending on the classpath). - Create the ViewModel after the rule has called
setMain. The rule runs before the test method, so creating it inside the test (or in a field initialized per test) is fine. StandardTestDispatcherqueues coroutines until the test suspends or callsrunCurrent()oradvanceUntilIdle(). That is what lets you see theLoadingstate.- Put
setMain/resetMainin a JUnit rule rather than at the start and end of each test; cleanup written after an assertion is skipped when the assertion fails. - Assert on the public
StateFlow, not on a privateMutableStateFlowor internal fields. The test should see what the UI observes. .valueworks for aMutableStateFlow-backed state. AstateIn(WhileSubscribed)state needs a collector, and one-off events in aSharedFloworChannelare easiest to test with Turbine.- On the JVM,
runTestreturnsTestResult, which is an alias forUnitthere, so@Test fun loads() = runTest { }compiles to a normal JUnit 4 test method. - Do not use
Thread.sleepin tests. AdelayinsiderunTest(or inside a fake running on the test dispatcher) is fine: it is skipped with virtual time.
Code example
A UserViewModel, a hand-written fake, a MainDispatcherRule, and JUnit 4 tests for the loading, success, and error states.
// ---- Production code (src/main) ----
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import java.io.IOException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
data class User(val id: Int, val name: String)
interface UserRepository {
suspend fun getUser(id: Int): User
}
sealed interface UiState {
data object Idle : UiState
data object Loading : UiState
data class Success(val name: String) : UiState
data class Error(val message: String) : UiState
}
class UserViewModel(private val repository: UserRepository) : ViewModel() {
private val _uiState = MutableStateFlow<UiState>(UiState.Idle)
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
fun loadUser(id: Int) {
_uiState.value = UiState.Loading
viewModelScope.launch {
_uiState.value = try {
UiState.Success(repository.getUser(id).name)
} catch (e: IOException) {
UiState.Error(e.message ?: "Network error")
}
}
}
}// ---- Test code (src/test) ----
import java.io.IOException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestWatcher
import org.junit.runner.Description
@OptIn(ExperimentalCoroutinesApi::class)
class MainDispatcherRule(
val testDispatcher: TestDispatcher = StandardTestDispatcher(),
) : TestWatcher() {
override fun starting(description: Description) = Dispatchers.setMain(testDispatcher)
override fun finished(description: Description) = Dispatchers.resetMain()
}
// Hand-written fake: the test sets what the next call returns
class FakeUserRepository : UserRepository {
var user = User(1, "Alice")
var error: IOException? = null
override suspend fun getUser(id: Int): User {
error?.let { throw it }
return user
}
}
@OptIn(ExperimentalCoroutinesApi::class)
class UserViewModelTest {
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
private val repository = FakeUserRepository()
@Test
fun `starts idle`() {
val viewModel = UserViewModel(repository)
assertEquals(UiState.Idle, viewModel.uiState.value)
}
@Test
fun `loadUser shows Loading, then Success`() = runTest {
val viewModel = UserViewModel(repository)
viewModel.loadUser(1)
assertEquals(UiState.Loading, viewModel.uiState.value) // launch is queued
advanceUntilIdle()
assertEquals(UiState.Success("Alice"), viewModel.uiState.value)
}
@Test
fun `loadUser shows Error when the repository fails`() = runTest {
repository.error = IOException("Timeout")
val viewModel = UserViewModel(repository)
viewModel.loadUser(1)
advanceUntilIdle()
assertEquals(UiState.Error("Timeout"), viewModel.uiState.value)
}
}- The rule installs a
StandardTestDispatcheras Main, andrunTestpicks up the same scheduler, soadvanceUntilIdle()runs the coroutineviewModelScopelaunched. - Because the dispatcher queues work, the test can see
Loadingright afterloadUserand before advancing. - The fake is a plain class with two properties. A failure is one line (
repository.error = ...), and a failing assertion points at state, not at stub wiring. - The ViewModel catches
IOExceptionrather than everyException, so coroutine cancellation is not swallowed.
Run the idea in plain Kotlin
The same state machine with a fake repository, and the async step modelled as a queued task that only runs when the "test" advances.
sealed class UiState {
object Idle : UiState() { override fun toString() = "Idle" }
object Loading : UiState() { override fun toString() = "Loading" }
data class Success(val name: String) : UiState()
data class Error(val message: String) : UiState()
}
interface UserRepository {
fun getUser(id: Int): String
}
class FakeUserRepository(private val name: String = "Alice", private val error: String? = null) : UserRepository {
override fun getUser(id: Int): String {
if (error != null) throw RuntimeException(error)
return name
}
}
// Stands in for StandardTestDispatcher: launched work waits in a queue
class Queue {
private val tasks = ArrayDeque<() -> Unit>()
fun launch(task: () -> Unit) { tasks.addLast(task) }
fun advanceUntilIdle() { while (tasks.isNotEmpty()) tasks.removeFirst()() }
}
class UserViewModel(private val repo: UserRepository, private val scope: Queue) {
var state: UiState = UiState.Idle
private set
fun loadUser(id: Int) {
state = UiState.Loading
scope.launch {
state = try {
UiState.Success(repo.getUser(id))
} catch (e: RuntimeException) {
UiState.Error(e.message ?: "error")
}
}
}
}
fun check(label: String, actual: UiState, expected: UiState) {
println(label + ": " + actual + if (actual == expected) " PASS" else " FAIL")
}
fun main() {
val queue1 = Queue()
val vm1 = UserViewModel(FakeUserRepository(), queue1)
check("initial", vm1.state, UiState.Idle)
vm1.loadUser(1)
check("after loadUser", vm1.state, UiState.Loading)
queue1.advanceUntilIdle()
check("after advance", vm1.state, UiState.Success("Alice"))
val queue2 = Queue()
val vm2 = UserViewModel(FakeUserRepository(error = "Timeout"), queue2)
vm2.loadUser(1)
queue2.advanceUntilIdle()
check("error path", vm2.state, UiState.Error("Timeout"))
}Expected output:
initial: Idle PASS
after loadUser: Loading PASS
after advance: Success(name=Alice) PASS
error path: Error(message=Timeout) PASS
In production
- Users reported that the profile screen showed a loading spinner forever after a network timeout.
- The screen did not crash, so crash reporting stayed quiet; the reports came from support tickets and reviews.
- The ViewModel set
Loading, then only handled the success case; the timeout exception was caught and logged, and the state stayedLoading. - The existing test only covered the success path, so CI stayed green.
- The catch block now sets
UiState.Errorwith a retry action. - A new test sets the fake repository to throw an
IOExceptionand assertsUiState.Error. - The team added "every Loading state has a test that leaves it with Error" to the review checklist for new screens.
- CI runs failed now and then with
expected:<Success(...)> but was:<Loading>. - The tests set Main to a real single-thread executor and used
Thread.sleep(1000)to wait for theviewModelScope.launchcoroutine. - On a busy shared CI runner the coroutine sometimes had not finished after one second.
- Because the failures were intermittent, developers re-ran the build and moved on.
- Every
Thread.sleepwas replaced withrunTestandadvanceUntilIdle(), so the tests no longer depend on real time. - A shared
MainDispatcherRuleinstalls aStandardTestDispatcheras Main, soviewModelScoperuns on the test scheduler. - The slow stubbed repository became a fake whose delay runs in virtual time, and these failures stopped.
Common mistakes
- Mocking a simple repository with MockK. A
coEvery { repo.getUser(any()) } returns ...per test is harder to read and to share than a small fake class. Keep MockK for checking interactions. - Forgetting to advance a StandardTestDispatcher. The launched coroutine stays queued, the state stays
Loading, and the assertion fails. CalladvanceUntilIdle()(orrunCurrent()) before asserting the final state. - Calling setMain and resetMain by hand. If an assertion fails before
resetMain, Main stays replaced for later tests in the same JVM, and failures start depending on test order. Use a JUnit rule. - Asserting on a private MutableStateFlow instead of the public StateFlow. Testing internals couples the test to implementation. Assert on
viewModel.uiState.value, the same state the UI collects. - Testing only the success path. The error branch is where users get stuck. Write a companion test for each failure the ViewModel handles.
- Reading .value of a stateIn(WhileSubscribed) state without a collector. It never leaves the initial value. Collect it with Turbine or in
backgroundScopefirst.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you structure a unit test for a ViewModel?”
“When do you use a fake instead of a mock (MockK)?”
“How do you handle coroutines in a ViewModel test?”
“How do you test a StateFlow that the UI collects?”
Quiz
What does advanceUntilIdle() do inside a runTest block?
Why is a hand-written fake usually preferred over MockK for a ViewModel's repository?
A test calls Dispatchers.setMain at its start and Dispatchers.resetMain at its end, and an assertion in between fails. What can happen?
Which expression reads the current value of a ViewModel's StateFlow without starting a coroutine?
0 of 4 answered
Mini task
Exercise: Test a ListViewModel with three states (15 min)
You have a ListViewModel that loads a list of items through a ListRepository.
-
Define the types (2 min). Create an
Itemdata class withid: Intandname: String, an interfaceListRepositorywithsuspend fun getItems(): List<Item>, and a sealedUiStatewithLoading,Success(items: List<Item>)andError(message: String). -
Write the ViewModel (3 min).
ListViewModel(repo: ListRepository) : ViewModel()exposesval uiState: StateFlow<UiState>backed by aMutableStateFlow(UiState.Loading).loadItems()setsLoading, launches onviewModelScope, callsrepo.getItems(), and setsSuccessor, onIOException,Error. -
Write the fake (2 min). Create
FakeListRepositorywithvar items: List<Item>andvar error: IOException?.getItems()throws the error if it is set, otherwise returns the items. -
Write three tests (5 min) with the
MainDispatcherRulefrom the example as@get:Rule:initial state is Loading: create the ViewModel and assertuiState.valueisUiState.Loading.loadItems transitions to Success: the fake returns two items; callloadItems(),advanceUntilIdle(), and assertSuccesswith two items.loadItems transitions to Error: set the fake's error; assertUiState.Errorafter advancing.
-
Run and verify (3 min). Run
./gradlew testDebugUnitTest --tests "*ListViewModelTest*". Then delete theadvanceUntilIdle()call from the success test and confirm it fails because the state is stillLoading, which shows the scheduler is in control.
Done condition: three tests pass, removing advanceUntilIdle makes the success test fail, and no test uses Thread.sleep or calls setMain outside the rule.