Skip to content
Tutorials Center
My learning

Topics

Lesson 81 of 104 ยท Testing

Unit Testing ViewModels and Flows

Test Android ViewModels with JUnit, runTest and test dispatchers: virtual time, Turbine-style flow assertions, fakes instead of mocks and a main dispatcher rule.

A ViewModel is the best place in an Android app to put logic, and the best place to test it. It has no views, needs no emulator and is plain Kotlin: give it a fake repository, call a function, look at the state. Such local unit tests run on your computer's JVM in milliseconds. The only difficulty is asynchrony: ViewModels launch coroutines, wait with delay, and expose flows that emit over time. A test that sleeps for real time is slow and flaky. Coroutine testing tools solve this with a test dispatcher and virtual time: the test controls the clock, so a 300 ms debounce takes no time to test and gives the same result every run.

This lesson covers the tools (JUnit, runTest, test dispatchers, Turbine) and the design habits that make code testable (injected dispatchers, fakes). The real test code is read-only, because the site cannot run the Android test tooling. The TryIts are stand-ins on Piston: they use a hand-built virtual-time dispatcher to show what kotlinx-coroutines-test does for you, along with a tiny flow recorder that behaves like Turbine. For the coroutine side of the story, see Testing Coroutines in the Kotlin tutorial, and for the code under test see ViewModel and UI State, Events and MVI-style Modelling.

Where tests live and what you need

Android projects have two test source sets:

  • app/src/test: local unit tests, run on the JVM. No device. This is where ViewModel, repository and use case tests go.
  • app/src/androidTest: instrumented tests, run on an emulator or a device (see Instrumented, Room and Navigation Tests).
Kotlin
// read-only: app/build.gradle.kts
dependencies {
    testImplementation("junit:junit:4.13.2")
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:<coroutines-version>")
    testImplementation("app.cash.turbine:turbine:<turbine-version>")
}

A JUnit test is a class with @Test methods. Kotlin lets you write test names as sentences with backticks, which makes failures easy to read: fun `load shows an error when the repository fails`(). Each test follows arrange, act, assert: set up the fakes, call the function, check the result.

Design for testability first

Three habits decide whether a ViewModel is easy to test:

  1. Take dependencies in the constructor (see Dependency Injection Concepts), and depend on interfaces, so tests can pass fakes.
  2. Inject dispatchers instead of writing Dispatchers.IO inside the class. The test then supplies a test dispatcher. (viewModelScope uses Dispatchers.Main, which does not exist in local tests, so you also replace it with Dispatchers.setMain; see below.)
  3. Expose state as a StateFlow, a single UiState, so the test asserts on one value, instead of poking at views.

Fakes over mocks

You can replace a dependency in a test in two ways. A mock (from a library such as MockK or Mockito) records calls and returns what you tell it per test: every { repo.fetch() } returns .... A fake is a small real implementation with in-memory behavior that you write once and reuse.

For repositories and data sources, prefer fakes:

  • A fake behaves: if you save a note, it returns that note later. A mock only does what each test scripts, so tests often replay the implementation's details.
  • Tests with fakes assert results (state, output), not interactions ("was save called once with these arguments"). They survive refactoring.
  • A fake can be shared by every test and by Compose previews.

Mocks still have their place for things that are hard to fake: a class that talks to the Android framework, or verifying that a side effect such as "analytics event sent" happened. Use them sparingly.

flowchart LR
    T["Test"] --> VM["ViewModel<br/>(real)"]
    VM --> F["FakeRepository<br/>(in memory)"]
    T -- "controls" --> F
    T -- "advances" --> D["Test dispatcher<br/>(virtual time)"]
    D -. "runs coroutines of" .-> VM
    T -- "asserts on" --> S["StateFlow of UiState"]

The test owns the fake, the clock and the assertions. The ViewModel under test is the real class.

Test dispatchers and virtual time

kotlinx-coroutines-test provides two test dispatchers that share a TestCoroutineScheduler (the virtual clock):

  • StandardTestDispatcher: queues launched coroutines and runs nothing until you tell it to: runCurrent(), advanceTimeBy(ms) or advanceUntilIdle(). You control the order, so you can see intermediate states such as "Loading".
  • UnconfinedTestDispatcher: starts coroutines eagerly, like Dispatchers.Unconfined. It is convenient for collecting flows in the background and for simple tests, but it can hide ordering problems.

runTest is the entry point: it runs your test body in a coroutine with a StandardTestDispatcher, skips every delay instantly by advancing the virtual clock, and fails the test if a coroutine throws or the test hangs. currentTime tells you how much virtual time has passed.

To make viewModelScope (which uses Dispatchers.Main) work in local tests, replace Main with a test dispatcher for every test using a JUnit rule:

Kotlin
// read-only
class MainDispatcherRule(
    val testDispatcher: TestDispatcher = UnconfinedTestDispatcher(),
) : TestWatcher() {
    override fun starting(description: Description) = Dispatchers.setMain(testDispatcher)
    override fun finished(description: Description) = Dispatchers.resetMain()
}

Here is a ViewModel test using these pieces. The ViewModel loads items through a repository, exposing uiState:

Kotlin
// read-only
class ItemsViewModelTest {

    @get:Rule
    val mainRule = MainDispatcherRule(StandardTestDispatcher())

    private val repository = FakeItemsRepository()

    @Test
    fun `load shows loading and then the items`() = runTest {
        val viewModel = ItemsViewModel(repository)
        repository.items = listOf("a", "b")

        viewModel.uiState.test {                       // Turbine
            assertEquals(UiState.Idle, awaitItem())
            viewModel.load()
            assertEquals(UiState.Loading, awaitItem())
            assertEquals(UiState.Content(listOf("a", "b")), awaitItem())
            cancelAndIgnoreRemainingEvents()
        }
    }

    @Test
    fun `a failed load shows an error and keeps working`() = runTest {
        repository.failure = IOException("No connection")
        val viewModel = ItemsViewModel(repository)

        viewModel.load()
        advanceUntilIdle()                              // let the coroutine finish

        assertEquals(UiState.Error("No connection"), viewModel.uiState.value)
    }
}

If the ViewModel and the test must share one scheduler, StandardTestDispatcher() created without arguments picks up the scheduler from Dispatchers.Main when set by the rule, so runTest and viewModelScope agree on virtual time.

Testing flows with Turbine

A flow emits several values over time, and a normal first() only sees one of them. Turbine wraps a flow in a small test harness: inside flow.test { ... } you call awaitItem() to get the next emission (waiting with a timeout), expectNoEvents() to assert that nothing happened, awaitComplete() or awaitError() for the end, and cancelAndIgnoreRemainingEvents() to finish. It makes ordering explicit: the test fails if emissions come in the wrong order or an unexpected one appears.

Two things to remember about StateFlow: it conflates, so if two values are set before the collector runs, the collector sees only the last one, and it always replays the current value on subscription (the first awaitItem() is the initial state). That is why the test above starts with assertEquals(UiState.Idle, awaitItem()).

For StateFlows built with stateIn(viewModelScope, WhileSubscribed(5_000), ...) there is an additional rule: the upstream only runs while someone collects. In a test, start a collector (Turbine's test {} or backgroundScope.launch { flow.collect {} }), otherwise the value stays at its initial value.

A stand-in test harness

Without an Android toolchain you cannot run runTest, so the first TryIt contains a small virtual-time dispatcher written by hand, plus a recorder that works like Turbine's test. This is a teaching model: it lets you watch the same behavior, but it is not the real library. The dispatcher queues tasks with a timestamp, and advanceTimeBy runs the ones that are due, while delay registers a wake-up on the virtual clock instead of sleeping. The tests are for a ViewModel with a fake repository that takes 50 ms to answer, like a network call.

Kotlin Testing a ViewModel with virtual time (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

All the waiting took no real time: 150 virtual milliseconds passed in a blink. The tests read like a script: act, advance the clock, assert the next state. Compare them with the Turbine version above; it is the same shape.

Testing time-based logic: a debounce

Time-dependent code is where virtual time pays off most. A search box that waits 300 ms after the last keystroke before calling the server (you will build this with flows in Collecting Flows Safely) would need real sleeping tests otherwise. With a controlled clock you can test the boundaries exactly: 299 ms later nothing has happened; at 300 ms the request starts.

The second TryIt tests a search ViewModel written with a plain restartable coroutine: each keystroke cancels the previous job and starts a new one that first waits.

Kotlin Testing a debounce at the exact boundary (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice what the test proves: three keystrokes made only one request, for the final text, and nothing happened one millisecond before the debounce ended. Doing this with real sleeping would take half a second per test and would still be timing-sensitive.

Common mistakes

  • Using real delay/Thread.sleep in tests. Use runTest and virtual time.
  • Forgetting to set the Main dispatcher. viewModelScope fails in local tests with "Module with the Main dispatcher had failed to initialize".
  • Hard-coding Dispatchers.IO in the class, so the test cannot control it. Inject it.
  • Collecting a StateFlow after the action. Start collecting (Turbine test) first, or you only see the final state.
  • Expecting every intermediate StateFlow value. It conflates; test the states that must be visible, with a standard dispatcher and controlled steps.
  • Over-mocking. A test that scripts every call of a mock mostly tests the mock. Use fakes for data layers.
  • Testing implementation, not behavior. Assert state and outputs, not private calls.
  • Leaking coroutines across tests. Create the ViewModel inside each test or use fresh fakes, and use backgroundScope for collectors started in runTest.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do local ViewModel tests use a test dispatcher with virtual time?

    A test dispatcher lets the test advance time itself, so delays and debounces cost no real time and give the same result on every run.
  2. 2. viewModelScope uses Dispatchers.Main. What must a local unit test do?

    Dispatchers.Main needs the Android main looper, which local tests do not have. setMain swaps in a test dispatcher and resetMain cleans up.
  3. 3. Why prefer a fake repository over a mock in most ViewModel tests?

    Tests with fakes assert on state and outputs, survive refactoring and reuse the same fake. Mocks suit hard-to-fake framework classes and verifying side effects.
  4. 4. With a StateFlow, what does the first awaitItem() in a Turbine test return?

    A StateFlow always has a value and replays it to new collectors, so the test first receives the initial state and then later changes.
  5. 5. A debounce waits 300 ms. In a virtual-time test, what can you assert that a real-time test could not do reliably?

    Virtual time lets you step the clock by single milliseconds, so boundary conditions are exact and the test is not flaky.

Summary

  • ViewModel tests are plain JVM tests in src/test: fast, no emulator, with fakes for dependencies.
  • Inject dependencies and dispatchers through constructors, and expose a single StateFlow<UiState>.
  • runTest skips delays with virtual time; StandardTestDispatcher queues work until you advance the clock, UnconfinedTestDispatcher runs eagerly.
  • Replace Dispatchers.Main with Dispatchers.setMain (a JUnit rule) so viewModelScope works locally.
  • Use Turbine to assert flow emissions in order (awaitItem, expectNoEvents); remember that StateFlow replays its current value and conflates.
  • Prefer fakes over mocks for data layers; assert behavior, not internals.
  • The real test code is read-only; the TryIts use a hand-built virtual-time dispatcher and recorder to model the same ideas.

Next: Testing Compose UI