Member-only story
Part 23 — Testing
Android Interview Prep — Complete Index
Testing questions are where architecture answers get audited. A candidate who described MVVM in Part 7 will be asked to test a ViewModel here — and if the design was sound, the test is three lines with no framework. The two topics that most reliably separate people are coroutine testing (topic 12) and fakes versus mocks (topic 11).
1. Unit testing a ViewModel (Coroutines + LiveData)
The canonical test, and the two rules that make it work at all.
class ProfileViewModelTest {
// RULE 1: LiveData needs this, or it throws
// "Cannot invoke observeForever on a background thread"
@get:Rule val instantRule = InstantTaskExecutorRule()
private val dispatcher = StandardTestDispatcher()
@Before fun setup() {
// RULE 2: viewModelScope uses Dispatchers.Main, which doesn't exist in a
// JVM test. Replace it, or you get "Module with the Main dispatcher failed"
Dispatchers.setMain(dispatcher)
}
@After fun tearDown() = Dispatchers.resetMain()
@Test fun `emits Ready after load`() = runTest {
val repo =…










