ViewModel tests

Learn Android ViewModel testing with Kotlin to master unit tests using fake repositories, test dispatchers, and state transition assertions. About 25 minutes.

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:

  1. 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".

  2. Main dispatcher. viewModelScope uses Dispatchers.Main.immediate, and Dispatchers.Main does not exist in a JVM test. A MainDispatcherRule calls Dispatchers.setMain(StandardTestDispatcher()) before each test and Dispatchers.resetMain() after it. runTest then reuses that dispatcher's scheduler, so runCurrent() and advanceUntilIdle() 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.

  3. State assertion. The ViewModel exposes a StateFlow<UiState>. With a MutableStateFlow behind it you can read viewModel.uiState.value after advancing the scheduler. If the state is built with stateIn(WhileSubscribed), it needs a collector first: Turbine's test { } or a collector in backgroundScope.

ConcernToolWhy
Coroutine controlrunTest, runCurrent(), advanceUntilIdle()Virtual time; no real waiting
DependencyHand-written fakeReadable, deterministic
Main dispatcherMainDispatcherRule with setMain / resetMainviewModelScope needs it
AssertionassertEquals(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.launch fails with IllegalStateException: 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.
  • StandardTestDispatcher queues coroutines until the test suspends or calls runCurrent() or advanceUntilIdle(). That is what lets you see the Loading state.
  • Put setMain / resetMain in 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 private MutableStateFlow or internal fields. The test should see what the UI observes.
  • .value works for a MutableStateFlow-backed state. A stateIn(WhileSubscribed) state needs a collector, and one-off events in a SharedFlow or Channel are easiest to test with Turbine.
  • On the JVM, runTest returns TestResult, which is an alias for Unit there, so @Test fun loads() = runTest { } compiles to a normal JUnit 4 test method.
  • Do not use Thread.sleep in tests. A delay inside runTest (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 StandardTestDispatcher as Main, and runTest picks up the same scheduler, so advanceUntilIdle() runs the coroutine viewModelScope launched.
  • Because the dispatcher queues work, the test can see Loading right after loadUser and 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 IOException rather than every Exception, 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

Endless spinner on the profile screen
  • 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 stayed Loading.
  • The existing test only covered the success path, so CI stayed green.
The fix
  • The catch block now sets UiState.Error with a retry action.
  • A new test sets the fake repository to throw an IOException and asserts UiState.Error.
  • The team added "every Loading state has a test that leaves it with Error" to the review checklist for new screens.
Flaky CI: ViewModel test suite
  • 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 the viewModelScope.launch coroutine.
  • 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.
The fix
  • Every Thread.sleep was replaced with runTest and advanceUntilIdle(), so the tests no longer depend on real time.
  • A shared MainDispatcherRule installs a StandardTestDispatcher as Main, so viewModelScope runs 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. Call advanceUntilIdle() (or runCurrent()) 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 backgroundScope first.

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.

  1. Define the types (2 min). Create an Item data class with id: Int and name: String, an interface ListRepository with suspend fun getItems(): List<Item>, and a sealed UiState with Loading, Success(items: List<Item>) and Error(message: String).

  2. Write the ViewModel (3 min). ListViewModel(repo: ListRepository) : ViewModel() exposes val uiState: StateFlow<UiState> backed by a MutableStateFlow(UiState.Loading). loadItems() sets Loading, launches on viewModelScope, calls repo.getItems(), and sets Success or, on IOException, Error.

  3. Write the fake (2 min). Create FakeListRepository with var items: List<Item> and var error: IOException?. getItems() throws the error if it is set, otherwise returns the items.

  4. Write three tests (5 min) with the MainDispatcherRule from the example as @get:Rule:

    • initial state is Loading: create the ViewModel and assert uiState.value is UiState.Loading.
    • loadItems transitions to Success: the fake returns two items; call loadItems(), advanceUntilIdle(), and assert Success with two items.
    • loadItems transitions to Error: set the fake's error; assert UiState.Error after advancing.
  5. Run and verify (3 min). Run ./gradlew testDebugUnitTest --tests "*ListViewModelTest*". Then delete the advanceUntilIdle() call from the success test and confirm it fails because the state is still Loading, 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.

Next: Compose UI tests