android5-5 Exercise 2: ViewModel tests with the fake ================================================= import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update // For previews and tests: same interface, no database class FakeNotesRepository : NotesRepository { private val notes = MutableStateFlow(listOf(Note(1, "Buy milk", 0L))) override fun getNotesStream(): Flow> = notes override suspend fun addNote(text: String) { notes.update { it + Note(it.size + 1L, text, 0L) } } override suspend fun deleteNote(note: Note) { notes.update { it - note } } } // app/src/test/.../NotesViewModelTest.kt (a plain JVM test: no emulator) @OptIn(ExperimentalCoroutinesApi::class) class NotesViewModelTest { @Before fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) @After fun tearDown() = Dispatchers.resetMain() @Test fun emptyNoteShowsMessage() = runTest { val viewModel = NotesViewModel(FakeNotesRepository()) viewModel.addNote(" ") assertEquals("A note cannot be empty", viewModel.uiState.value.userMessage) } } Second test: @Test fun addedNoteAppearsInState() = runTest { val viewModel = NotesViewModel(FakeNotesRepository()) val job = launch { viewModel.uiState.collect { } } // start the stateIn flow viewModel.addNote("Call Ada") assertTrue(viewModel.uiState.value.notes.any { it.text == "Call Ada" }) job.cancel() } Dependencies (general knowledge, check): testImplementation of org.jetbrains.kotlinx:kotlinx-coroutines-test, junit. The collector is needed because uiState uses WhileSubscribed (Chapter 3): without a collector the upstream does not run. Code unrun.