The ViewModel is where a Compose screen's behavior lives: what the screen shows while loading, what happens when the user saves, which error appears when the network fails. It is plain Kotlin and runs on the JVM, so its tests take milliseconds and need no emulator. That makes it the best-value test in an Android app. This post tests a small note editor's ViewModel with a fake repository, coroutine test dispatchers, Turbine and SavedStateHandle .
The code under test
The editor loads a note by id, lets the user change the title and body, and saves. Its state is a single StateFlow<EditorUiState> , and the important parts look like this:
class EditorViewModel ( private val repository : NotesRepository , private val savedStateHandle : SavedStateHandle , ) : ViewModel () {
private val noteId : Long ? = savedStateHandle . get < Long >( "noteId" ) private val _state = MutableStateFlow ( EditorUiState ()) val state : StateFlow < EditorUiState > = _state . asStateFlow ()
init { viewModelScope .…