Testare ViewModel e Flow
Testi la logica con dispatcher di test.
Testare ViewModel e Flow è una lezione Jetpack Compose Academy gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Jetpack Compose Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Jetpack Compose Academy include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Test Logic Without the UI
A ViewModel holds your screen logic, so you can test it directly with plain JUnit. No emulator or rendering needed, which makes these tests fast. ⚡
Arrange, Act, Assert
ViewModel tests follow a simple rhythm: create the ViewModel, call a function, then assert the new state. Keep each test focused on one behavior.
val vm = CounterViewModel()
vm.increment()
assertEquals(1, vm.count)The Coroutine Challenge
Many ViewModels launch coroutines, which run on Dispatchers.Main. In tests there is no main looper, so you must swap in a test dispatcher instead.
StandardTestDispatcher
A StandardTestDispatcher gives you full control over coroutine timing. Tasks queue up and run only when you advance the virtual clock.
val dispatcher = StandardTestDispatcher()Replace the Main Dispatcher
Use Dispatchers.setMain before each test to inject your test dispatcher, then call resetMain afterward to leave global state clean.
Dispatchers.setMain(dispatcher)runTest
Wrap suspending test bodies in runTest. It provides a coroutine scope with a virtual clock so delays resolve instantly, not in real seconds.
@Test fun loads() = runTest {
// suspend calls run here
}Quick Check
Your ViewModel launches coroutines on the main dispatcher. What lets a unit test control their execution?
Advancing the Clock
With a StandardTestDispatcher, queued coroutines wait. Call advanceUntilIdle inside runTest to run them all, then check the final state.
advanceUntilIdle()
assertEquals(Loaded, vm.uiState.value)Testing a StateFlow
ViewModels often expose a StateFlow. Its current snapshot lives in .value, so you can read and assert it directly after advancing the clock.
assertEquals(0, vm.count.value)Collecting Flow Emissions
To capture a sequence of emissions, the Turbine library makes Flow testing easy with awaitItem, asserting each value as it arrives.
vm.events.test {
assertEquals(Saved, awaitItem())
}Fake Your Dependencies
Inject a fake repository that returns canned data. This keeps tests fast and lets you simulate success and error paths without a real network.
val vm = NewsViewModel(FakeRepo())Clean Teardown
Always pair setMain with resetMain in your teardown. Leaving a test dispatcher installed can leak into and break other tests in the suite.
@After fun tearDown() {
Dispatchers.resetMain()
}Recap: ViewModels & Flows
Test logic without UI by swapping in a test dispatcher, running code in runTest, and asserting StateFlow values. Fast, focused, reliable tests. 🏁
Domande Frequenti
La lezione «Testare ViewModel e Flow» è gratuita?
Sì — il testo completo di «Testare ViewModel e Flow» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Jetpack Compose Academy, passa a CoddyKit PRO. Il corso Jetpack Compose Academy include 4 lezioni in totale.
Cosa imparerò in «Testare ViewModel e Flow»?
Testi la logica con dispatcher di test. Eserciti Jetpack Compose Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Jetpack Compose Academy?
Non è richiesta alcuna esperienza precedente. Jetpack Compose Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Testare ViewModel e Flow»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Jetpack Compose Academy?
Sì. Ogni lezione Jetpack Compose Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- createComposeRule e finder
- Asserzioni ed esecuzione di azioni
- Semantics e tag di test
- Testare ViewModel e Flow