Skip to content

Unit testing viewmodel

Unit Testing Viewmodel Deep Dive

Overview

ViewModel unit tests should validate state transitions and intent handling, not framework internals.

Core Concepts

  • Inputs: intents/actions/events.
  • Outputs: immutable UI state + one-off events.
  • Dependencies replaced with deterministic fakes/mocks.

Test Pyramid and Strategy

  • Keep ViewModel tests at unit layer for speed.
  • Verify happy path, error path, and loading path.

Tooling and Infrastructure

  • runTest + test dispatcher.
  • Assert state timeline, not only final state.

Flaky Test Mitigation

  • Avoid real dispatcher/thread usage.
  • Control time for debounce/retry logic.

Code Examples

@Test
fun loadProfile_updatesUiState() = runTest {
    // Given fake repository success
    // When load invoked
    // Then loading -> content state emitted
}

Common Interview Questions

  • Q: What exactly do you assert in ViewModel tests? A: Answer by test pyramid intent: unit for logic speed, integration for boundaries, and end-to-end for critical journeys with flakiness controls.
  • Q: How do you test one-off events safely? A: Answer by test pyramid intent: unit for logic speed, integration for boundaries, and end-to-end for critical journeys with flakiness controls.

Production Considerations

  • Keep ViewModel APIs deterministic and test-friendly.

Performance Insights

  • Fast unit suites enable frequent refactors.

Senior-Level Insights

  • Good tests encode domain behavior, not implementation noise.