Interview frequency: …
Short answer
By mocking the dependencies through mockk() and specifying their expected behavior using every or coEvery, then verifying function calls via verify or coVerify.
Explanation
MockK is a library designed natively for Kotlin and supports suspend functions and coroutines seamlessly through coEvery and coVerify, unlike Mockito, which requires extra setup. It lets you test the ViewModel in isolation from the network and the database by replacing the repository with a mocked copy and confirming that the UiState reflects the result correctly.
Code example
class UserViewModelTest {
private val repository = mockk<UserRepository>()
private lateinit var viewModel: UserViewModel
@Test
fun loadUser_updatesStateToSuccess() = runTest {
coEvery { repository.getUser("1") } returns User(1, "Sara")
viewModel = UserViewModel(repository)
viewModel.loadUser("1")
assertEquals(User(1, "Sara"), viewModel.uiState.value.user)
coVerify(exactly = 1) { repository.getUser("1") }
}
}Common mistakes
- Overusing mocks for everything; it is always preferable to use simple real in-memory fake repositories whenever available to reduce test brittleness.