ViewModelとFlowのテスト
テスト用Dispatcherでロジックをユニットテストします。
「ViewModelとFlowのテスト」はCoddyKit上の無料Jetpack Compose Academyレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはJetpack Compose Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Jetpack Compose Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
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. 🏁
よくある質問
「ViewModelとFlowのテスト」レッスンは無料ですか?
はい。「ViewModelとFlowのテスト」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Jetpack Compose Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Jetpack Compose Academyコースには全4レッスンが含まれています。
「ViewModelとFlowのテスト」で何を学びますか?
テスト用Dispatcherでロジックをユニットテストします。 ブラウザで直接実行するハンズオンコードでJetpack Compose Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Jetpack Compose Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのJetpack Compose Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「ViewModelとFlowのテスト」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このJetpack Compose Academyレッスンでコードを書いて実行できますか?
はい。すべてのJetpack Compose Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- createComposeRuleとFinder
- アサーションとアクションの実行
- セマンティクスとテストタグ
- ViewModelとFlowのテスト