Menguji ViewModels & Flow
Uji logika secara unit dengan dispatcher test.
Menguji ViewModels & Flow adalah pelajaran Jetpack Compose Academy gratis di CoddyKit. Ini adalah pelajaran 4 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Jetpack Compose Academy, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Jetpack Compose Academy mencakup 4 pelajaran total.
Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.
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. 🏁
Pertanyaan yang Sering Diajukan
Apakah pelajaran “Menguji ViewModels & Flow” gratis?
Ya — teks lengkap “Menguji ViewModels & Flow” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Jetpack Compose Academy, upgrade ke CoddyKit PRO. Kursus Jetpack Compose Academy mencakup 4 pelajaran total.
Apa yang akan aku pelajari di “Menguji ViewModels & Flow”?
Uji logika secara unit dengan dispatcher test. Kamu berlatih Jetpack Compose Academy dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.
Apakah aku perlu pengalaman untuk memulai Jetpack Compose Academy?
Tidak diperlukan pengalaman sebelumnya. Jetpack Compose Academy di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 4 dari 4.
Berapa lama pelajaran “Menguji ViewModels & Flow” memakan waktu?
Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.
Bisakah aku menulis dan menjalankan kode dalam pelajaran Jetpack Compose Academy ini?
Ya. Setiap pelajaran Jetpack Compose Academy menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.
Semua pelajaran dalam kursus ini
- createComposeRule & Pencari
- Assertion & Menjalankan Tindakan
- Semantik & Tag Test
- Menguji ViewModels & Flow