{"id":169,"date":"2026-10-19T03:04:00","date_gmt":"2026-10-19T03:04:00","guid":{"rendered":"https:\/\/moiks.com\/blog\/?p=169"},"modified":"2026-11-06T08:48:29","modified_gmt":"2026-11-06T08:48:29","slug":"kotlin-flow-testing-in-android-turbine-runtest-testdispatchers","status":"publish","type":"post","link":"https:\/\/moiks.com\/blog\/kotlin-flow-testing-in-android-turbine-runtest-testdispatchers\/","title":{"rendered":"Kotlin Flow Testing in Android: Turbine, runTest &#038; TestDispatchers"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Testing asynchronous code is an essential skill for modern Android developers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Applications built with Kotlin Coroutines and Flow frequently perform asynchronous operations such as fetching API data, observing Room databases, updating UI state, and handling background tasks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These operations can be difficult to test using traditional synchronous testing techniques.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Fortunately, Kotlin provides dedicated testing utilities that make coroutine and Flow testing predictable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we&#8217;ll learn how to test <strong>Kotlin Flow, StateFlow, SharedFlow, and Android ViewModel<\/strong> using:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>kotlinx-coroutines-test<\/li>\n\n\n\n<li>runTest()<\/li>\n\n\n\n<li>StandardTestDispatcher<\/li>\n\n\n\n<li>UnconfinedTestDispatcher<\/li>\n\n\n\n<li>TestCoroutineScheduler<\/li>\n\n\n\n<li>Turbine<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll also build a practical ViewModel testing example using Kotlin Flow and Jetpack Compose architecture.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What You&#8217;ll Learn<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">By the end of this tutorial, you&#8217;ll understand:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Why asynchronous Flow testing matters<\/li>\n\n\n\n<li>Setting up coroutine testing dependencies<\/li>\n\n\n\n<li>Testing cold Flows<\/li>\n\n\n\n<li>Understanding runTest()<\/li>\n\n\n\n<li>Virtual time and TestCoroutineScheduler<\/li>\n\n\n\n<li>StandardTestDispatcher vs UnconfinedTestDispatcher<\/li>\n\n\n\n<li>Testing Flow emissions with Turbine<\/li>\n\n\n\n<li>Testing StateFlow<\/li>\n\n\n\n<li>Testing SharedFlow<\/li>\n\n\n\n<li>Testing Flow operators<\/li>\n\n\n\n<li>Testing debounce()<\/li>\n\n\n\n<li>Testing retryWhen()<\/li>\n\n\n\n<li>Testing loading, success, and error states<\/li>\n\n\n\n<li>Testing Android ViewModel<\/li>\n\n\n\n<li>Replacing Dispatchers.Main<\/li>\n\n\n\n<li>Common testing mistakes<\/li>\n\n\n\n<li>Production testing best practices<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s begin!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">1. Why Test Kotlin Flow?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Kotlin Flow is commonly used for asynchronous streams.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Examples include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Room database observations<\/li>\n\n\n\n<li>API responses<\/li>\n\n\n\n<li>Search queries<\/li>\n\n\n\n<li>Form validation<\/li>\n\n\n\n<li>Download progress<\/li>\n\n\n\n<li>UI state updates<\/li>\n\n\n\n<li>Real-time data<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">These streams may emit multiple values over time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A good test should verify:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Which values are emitted.<\/li>\n\n\n\n<li>The order of emissions.<\/li>\n\n\n\n<li>Whether errors are handled correctly.<\/li>\n\n\n\n<li>Whether delays and retries work.<\/li>\n\n\n\n<li>Whether state changes match expectations.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Imagine a ViewModel that loads products.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Its UI state may change as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Loading\n   |\n   v\nSuccess(products)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If the request fails:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Loading\n   |\n   v\nError(message)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Unit tests can verify both scenarios without launching the Android application.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">2. Add Kotlin Flow Testing Dependencies<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Add the testing dependencies to your Android module.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">build.gradle.kts<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>dependencies {\n\n    testImplementation(\n        \"junit:junit:4.13.2\"\n    )\n\n    testImplementation(\n        \"org.jetbrains.kotlinx:kotlinx-coroutines-test:&lt;version&gt;\"\n    )\n\n    testImplementation(\n        \"app.cash.turbine:turbine:&lt;version&gt;\"\n    )\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Replace <code>&lt;version&gt;<\/code> with compatible stable releases.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>kotlinx-coroutines-test<\/code> version should match your Kotlin Coroutines dependency version.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What Does Each Library Do?<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Library<\/th><th>Purpose<\/th><\/tr><tr><td>JUnit<\/td><td>Runs and organizes unit tests<\/td><\/tr><tr><td>kotlinx-coroutines-test<\/td><td>Provides coroutine test scopes, dispatchers, and virtual time<\/td><\/tr><tr><td>Turbine<\/td><td>Simplifies testing Flow emissions<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">These examples use local JVM tests under:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>app\/src\/test\/java\/<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">3. Your First Kotlin Flow Unit Test<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s begin with a simple cold Flow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production Code<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun numbersFlow(): Flow&lt;Int&gt; = flow {\n    emit(10)\n    emit(20)\n    emit(30)\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Unit Test<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `numbers flow emits expected values`() = runTest {\n\n    val results = numbersFlow().toList()\n\n    assertEquals(\n        listOf(10, 20, 30),\n        results\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The test collects all Flow emissions into a list.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It then compares the actual values against the expected values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>toList()<\/code> waits for the Flow to complete.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It works well with finite Flows.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not use it directly on StateFlow or SharedFlow because these hot streams normally never complete.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">4. Understanding runTest()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>runTest()<\/code> function is designed for testing coroutine-based code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `coroutine delay uses virtual time`() = runTest {\n\n    delay(5000)\n\n    assertTrue(true)\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The delay is controlled by the test scheduler.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The test does not need to wait five real seconds for a virtual-time delay.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Deterministic coroutine testing<\/li>\n\n\n\n<li>Virtual-time support<\/li>\n\n\n\n<li>Controlled coroutine execution<\/li>\n\n\n\n<li>Structured test scopes<\/li>\n\n\n\n<li>Better asynchronous error reporting<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Virtual time applies to delays managed by the test scheduler.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Code running on unrelated real dispatchers may still use real time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For reliable tests, inject dispatchers and avoid hardcoded <code>Dispatchers.IO<\/code> or <code>Dispatchers.Default<\/code> where scheduling control is necessary.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">5. Understanding TestCoroutineScheduler<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">TestCoroutineScheduler manages virtual time for coroutine test dispatchers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `advance virtual time`() = runTest {\n\n    var completed = false\n\n    launch {\n\n        delay(3000)\n\n        completed = true\n    }\n\n    assertFalse(completed)\n\n    advanceTimeBy(3000)\n\n    runCurrent()\n\n    assertTrue(completed)\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The test starts a coroutine.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The coroutine suspends for three seconds of virtual time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>advanceTimeBy(3000)<\/code> advances the scheduler clock.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>runCurrent()<\/code> executes tasks scheduled at the current virtual time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The test verifies that the operation completed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Useful Scheduler Functions<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Function<\/th><th>Purpose<\/th><\/tr><tr><td>runCurrent()<\/td><td>Execute tasks scheduled at the current time<\/td><\/tr><tr><td>advanceTimeBy()<\/td><td>Advance virtual time by a duration<\/td><\/tr><tr><td>advanceUntilIdle()<\/td><td>Execute scheduled work until no runnable tasks remain<\/td><\/tr><tr><td>currentTime<\/td><td>Read current virtual time<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">6. StandardTestDispatcher<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">StandardTestDispatcher provides controlled coroutine scheduling.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Coroutines launched on it are queued until the test scheduler runs them.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `standard dispatcher queues coroutine`() = runTest {\n\n    var value = 0\n\n    launch(StandardTestDispatcher(testScheduler)) {\n        value = 10\n    }\n\n    assertEquals(0, value)\n\n    runCurrent()\n\n    assertEquals(10, value)\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The coroutine is scheduled but does not execute immediately.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">After calling <code>runCurrent()<\/code>, the scheduled coroutine runs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">When to Use It<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StandardTestDispatcher is useful when testing:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Precise coroutine execution order<\/li>\n\n\n\n<li>Loading state transitions<\/li>\n\n\n\n<li>Delayed operations<\/li>\n\n\n\n<li>Debounce behavior<\/li>\n\n\n\n<li>Concurrent coroutine interactions<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">It is generally a good default for controlled coroutine tests.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">7. UnconfinedTestDispatcher<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">UnconfinedTestDispatcher eagerly enters coroutine builders when they are launched.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@OptIn(ExperimentalCoroutinesApi::class)\n@Test\nfun `unconfined dispatcher starts coroutine eagerly`() = runTest {\n\n    var value = 0\n\n    launch(UnconfinedTestDispatcher(testScheduler)) {\n        value = 10\n    }\n\n    assertEquals(10, value)\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The launched coroutine begins executing immediately.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, UnconfinedTestDispatcher does not guarantee normal sequential execution order across suspensions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Comparison<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Feature<\/th><th>StandardTestDispatcher<\/th><th>UnconfinedTestDispatcher<\/th><\/tr><tr><td>Starts launched coroutine eagerly<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Scheduling control<\/td><td>Explicit<\/td><td>Less explicit<\/td><\/tr><tr><td>Useful for precise ordering<\/td><td>Yes<\/td><td>Less suitable<\/td><\/tr><tr><td>Useful for starting collectors<\/td><td>Yes<\/td><td>Yes<\/td><\/tr><tr><td>Typical use<\/td><td>Deterministic scheduling<\/td><td>Simple eager collection<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Prefer StandardTestDispatcher when execution order matters.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use UnconfinedTestDispatcher selectively, especially when a collector must begin observing before state changes occur.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">8. What Is Turbine?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Turbine is a testing library designed for Kotlin Flow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It provides a convenient way to assert emitted values.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Without Turbine<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `flow emits values`() = runTest {\n\n    val values = flowOf(1, 2, 3).toList()\n\n    assertEquals(\n        listOf(1, 2, 3),\n        values\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">With Turbine<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `flow emits values using turbine`() = runTest {\n\n    flowOf(1, 2, 3).test {\n\n        assertEquals(1, awaitItem())\n\n        assertEquals(2, awaitItem())\n\n        assertEquals(3, awaitItem())\n\n        awaitComplete()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>test {}<\/code> extension collects Flow emissions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>awaitItem()<\/code> waits for the next value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>awaitComplete()<\/code> verifies normal completion.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Turbine is especially useful for testing streams that emit multiple states over time.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">9. Important Turbine Functions<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Function<\/th><th>Purpose<\/th><\/tr><tr><td>test {}<\/td><td>Collect and test a Flow<\/td><\/tr><tr><td>awaitItem()<\/td><td>Wait for the next emitted value<\/td><\/tr><tr><td>awaitComplete()<\/td><td>Verify normal completion<\/td><\/tr><tr><td>awaitError()<\/td><td>Verify terminal failure<\/td><\/tr><tr><td>expectNoEvents()<\/td><td>Verify no events are available<\/td><\/tr><tr><td>cancelAndIgnoreRemainingEvents()<\/td><td>Cancel collection and discard pending events<\/td><\/tr><tr><td>skipItems()<\/td><td>Skip a specified number of emissions<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `turbine verifies flow completion`() = runTest {\n\n    flowOf(\"Android\", \"Kotlin\").test {\n\n        assertEquals(\n            \"Android\",\n            awaitItem()\n        )\n\n        assertEquals(\n            \"Kotlin\",\n            awaitItem()\n        )\n\n        awaitComplete()\n    }\n}<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">10. Testing Flow Errors with Turbine<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s create a Flow that throws an exception.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production Code<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun errorFlow(): Flow&lt;Int&gt; = flow {\n\n    emit(1)\n\n    throw IllegalStateException(\n        \"Something went wrong\"\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Unit Test<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `flow emits error`() = runTest {\n\n    errorFlow().test {\n\n        assertEquals(1, awaitItem())\n\n        val error = awaitError()\n\n        assertTrue(\n            error is IllegalStateException\n        )\n\n        assertEquals(\n            \"Something went wrong\",\n            error.message\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The test verifies the first emitted value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It then checks that the Flow terminates with the expected exception.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is useful for testing repository and data-processing failures.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">11. Testing StateFlow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow represents the latest observable state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s create a simple counter ViewModel.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production Code<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class CounterViewModel : ViewModel() {\n\n    private val _count = MutableStateFlow(0)\n\n    val count: StateFlow&lt;Int&gt; =\n        _count.asStateFlow()\n\n    fun increment() {\n\n        _count.update { current -&gt;\n            current + 1\n        }\n    }\n\n    fun reset() {\n\n        _count.value = 0\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Simple StateFlow Test<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `counter increments correctly`() {\n\n    val viewModel = CounterViewModel()\n\n    assertEquals(0, viewModel.count.value)\n\n    viewModel.increment()\n\n    assertEquals(1, viewModel.count.value)\n\n    viewModel.reset()\n\n    assertEquals(0, viewModel.count.value)\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow exposes its current value through <code>.value<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For many state-focused tests, checking <code>.value<\/code> is simpler than collecting emissions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use direct state assertions when you only need to verify the latest state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use Turbine when testing meaningful emission sequences.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">12. Testing StateFlow Emissions with Turbine<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We can also verify a sequence of state changes.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `counter emits state updates`() = runTest {\n\n    val viewModel = CounterViewModel()\n\n    viewModel.count.test {\n\n        assertEquals(0, awaitItem())\n\n        viewModel.increment()\n\n        assertEquals(1, awaitItem())\n\n        viewModel.increment()\n\n        assertEquals(2, awaitItem())\n\n        cancelAndIgnoreRemainingEvents()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The test begins by receiving the initial StateFlow value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each increment updates the current state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Turbine verifies the resulting emissions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow is conflated.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If values change faster than a collector can process them, intermediate values may be skipped.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not assume every intermediate assignment will be observed in asynchronous tests.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">13. Testing SharedFlow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">SharedFlow is commonly used to broadcast events.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production Code<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class EventManager {\n\n    private val _events =\n        MutableSharedFlow&lt;String&gt;()\n\n    val events: SharedFlow&lt;String&gt; =\n        _events.asSharedFlow()\n\n    suspend fun sendEvent(message: String) {\n\n        _events.emit(message)\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Unit Test<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `shared flow emits event`() = runTest {\n\n    val manager = EventManager()\n\n    manager.events.test {\n\n        manager.sendEvent(\"Download completed\")\n\n        assertEquals(\n            \"Download completed\",\n            awaitItem()\n        )\n\n        cancelAndIgnoreRemainingEvents()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Turbine starts collecting before the event is emitted.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is important because a default SharedFlow does not replay values to late subscribers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Best Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Always consider subscriber timing when testing SharedFlow.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">14. Testing Flow map() Operator<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Flow operators can be tested independently.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production Code<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun doubledNumbers(): Flow&lt;Int&gt; {\n\n    return flowOf(1, 2, 3)\n        .map { number -&gt;\n            number * 2\n        }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Unit Test<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `map doubles numbers`() = runTest {\n\n    doubledNumbers().test {\n\n        assertEquals(2, awaitItem())\n\n        assertEquals(4, awaitItem())\n\n        assertEquals(6, awaitItem())\n\n        awaitComplete()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The test verifies that each input is transformed correctly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This pattern works for many Flow operators, including filter, distinctUntilChanged, and combine.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">15. Testing debounce() with Virtual Time<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The debounce operator waits for a period without new emissions before forwarding the latest value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is commonly used in search interfaces.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production Code<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun searchQueries(\n    queries: Flow&lt;String&gt;\n): Flow&lt;String&gt; {\n\n    return queries.debounce(300)\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Unit Test<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@OptIn(FlowPreview::class)\n@Test\nfun `debounce emits latest query`() = runTest {\n\n    val queries = MutableSharedFlow&lt;String&gt;(\n        extraBufferCapacity = 1\n    )\n\n    val results = mutableListOf&lt;String&gt;()\n\n    backgroundScope.launch(\n        UnconfinedTestDispatcher(testScheduler)\n    ) {\n\n        searchQueries(queries).collect { query -&gt;\n\n            results.add(query)\n        }\n    }\n\n    queries.emit(\"A\")\n\n    advanceTimeBy(100)\n\n    queries.emit(\"An\")\n\n    advanceTimeBy(100)\n\n    queries.emit(\"Android\")\n\n    advanceTimeBy(300)\n\n    runCurrent()\n\n    assertEquals(\n        listOf(\"Android\"),\n        results\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The test emits three search queries.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each new query resets the debounce timer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Only the latest query is emitted after the quiet period.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why Use Virtual Time?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The test can verify debounce behavior without waiting for real delays.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This makes tests faster and more deterministic.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">16. Testing retryWhen()<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Retry logic is another important asynchronous behavior to test.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production Code<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>fun retryableFlow(): Flow&lt;String&gt; {\n\n    var attempts = 0\n\n    return flow {\n\n        attempts++\n\n        if (attempts &lt; 3) {\n\n            throw IOException(\n                \"Temporary network failure\"\n            )\n        }\n\n        emit(\"Success\")\n\n    }.retryWhen { cause, attempt -&gt;\n\n        if (\n            cause is IOException &amp;&amp;\n            attempt &lt; 2\n        ) {\n\n            delay(1000)\n\n            true\n\n        } else {\n\n            false\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Unit Test<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `retry succeeds after temporary failures`() = runTest {\n\n    retryableFlow().test {\n\n        assertEquals(\n            \"Success\",\n            awaitItem()\n        )\n\n        awaitComplete()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Flow fails twice.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">retryWhen restarts upstream collection.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The third attempt succeeds.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The test verifies that the final result is emitted.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">runTest uses virtual time for the retry delays when the Flow executes on the test scheduler.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">17. Replacing Dispatchers.Main in Unit Tests<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Android ViewModel commonly uses <code>viewModelScope<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">That scope relies on Dispatchers.Main.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Local JVM tests do not provide the Android main thread dispatcher automatically.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We can replace it with a test dispatcher.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">MainDispatcherRule.kt<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@OptIn(ExperimentalCoroutinesApi::class)\nclass MainDispatcherRule(\n    val testDispatcher: TestDispatcher =\n        StandardTestDispatcher()\n) : TestWatcher() {\n\n    override fun starting(\n        description: Description\n    ) {\n\n        Dispatchers.setMain(testDispatcher)\n    }\n\n    override fun finished(\n        description: Description\n    ) {\n\n        Dispatchers.resetMain()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Required Imports<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.ExperimentalCoroutinesApi\nimport kotlinx.coroutines.test.StandardTestDispatcher\nimport kotlinx.coroutines.test.TestDispatcher\nimport kotlinx.coroutines.test.resetMain\nimport kotlinx.coroutines.test.setMain\n\nimport org.junit.rules.TestWatcher\nimport org.junit.runner.Description<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The rule replaces Dispatchers.Main before each test.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It restores the original dispatcher afterward.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This allows ViewModel coroutine tests to run on the local JVM.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create test dispatchers that share the same TestCoroutineScheduler.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When Dispatchers.Main is replaced with a TestDispatcher, subsequently created test dispatchers and runTest scopes can share its scheduler.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid accidentally using multiple unrelated schedulers in the same test.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">Practical Android Mini-Project: Testing a Product ViewModel<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s build a complete ViewModel testing example.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Our application architecture will use:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Product model<\/li>\n\n\n\n<li>Product repository interface<\/li>\n\n\n\n<li>Fake repository<\/li>\n\n\n\n<li>ProductUiState<\/li>\n\n\n\n<li>ProductViewModel<\/li>\n\n\n\n<li>StateFlow<\/li>\n\n\n\n<li>Turbine<\/li>\n\n\n\n<li>runTest<\/li>\n\n\n\n<li>MainDispatcherRule<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll test:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Initial loading state<\/li>\n\n\n\n<li>Successful product loading<\/li>\n\n\n\n<li>Failed product loading<\/li>\n\n\n\n<li>Retry behavior<\/li>\n\n\n\n<li>StateFlow emissions<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">18. Create the Product Model<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>data class Product(\n    val id: Int,\n    val name: String,\n    val price: Double\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This represents a product in our sample application.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">19. Create the Repository Interface<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>interface ProductRepository {\n\n    suspend fun getProducts(): List&lt;Product&gt;\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why Use an Interface?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">An interface allows the ViewModel to depend on an abstraction.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">During testing, we can replace the real repository with a fake implementation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This improves testability and supports clean architecture.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">20. Create the Fake Product Repository<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>class FakeProductRepository : ProductRepository {\n\n    var shouldFail = false\n\n    override suspend fun getProducts(): List&lt;Product&gt; {\n\n        delay(500)\n\n        if (shouldFail) {\n\n            throw IOException(\n                \"Simulated network failure\"\n            )\n        }\n\n        return listOf(\n            Product(\n                id = 1,\n                name = \"Android Phone\",\n                price = 19999.0\n            ),\n            Product(\n                id = 2,\n                name = \"Bluetooth Speaker\",\n                price = 2499.0\n            )\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The fake repository simulates both success and failure.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Set shouldFail to true to trigger an exception.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Set it to false to return sample products.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>No real API required<\/li>\n\n\n\n<li>Fast execution<\/li>\n\n\n\n<li>Predictable results<\/li>\n\n\n\n<li>Easy failure simulation<\/li>\n\n\n\n<li>Independent ViewModel testing<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">21. Create ProductUiState<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>sealed interface ProductUiState {\n\n    data object Loading : ProductUiState\n\n    data class Success(\n        val products: List&lt;Product&gt;\n    ) : ProductUiState\n\n    data class Error(\n        val message: String\n    ) : ProductUiState\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This model represents the screen&#8217;s observable state.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">22. Create ProductViewModel<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>class ProductViewModel(\n    private val repository: ProductRepository\n) : ViewModel() {\n\n    private val _uiState =\n        MutableStateFlow&lt;ProductUiState&gt;(\n            ProductUiState.Loading\n        )\n\n    val uiState: StateFlow&lt;ProductUiState&gt; =\n        _uiState.asStateFlow()\n\n    private var loadJob: Job? = null\n\n    init {\n        loadProducts()\n    }\n\n    fun loadProducts() {\n\n        loadJob?.cancel()\n\n        loadJob = viewModelScope.launch {\n\n            _uiState.value = ProductUiState.Loading\n\n            try {\n\n                val products = repository.getProducts()\n\n                _uiState.value =\n                    ProductUiState.Success(products)\n\n            } catch (exception: CancellationException) {\n\n                throw exception\n\n            } catch (exception: Exception) {\n\n                _uiState.value =\n                    ProductUiState.Error(\n                        \"Unable to load products\"\n                    )\n            }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel loads products when initialized.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It exposes its current UI state through StateFlow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When the repository succeeds, the state becomes Success.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When the repository fails, the state becomes Error.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel preserves coroutine cancellation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production Note<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In a production Android application, the repository can be provided through Hilt dependency injection.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For this tutorial, constructor injection keeps the example simple and testable.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">23. Test Initial Loading State<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s verify that the initial state is Loading.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@OptIn(ExperimentalCoroutinesApi::class)\nclass ProductViewModelTest {\n\n    @get:Rule\n    val mainDispatcherRule = MainDispatcherRule()\n\n    @Test\n    fun `initial state is loading`() = runTest {\n\n        val repository = FakeProductRepository()\n\n        val viewModel = ProductViewModel(repository)\n\n        assertEquals(\n            ProductUiState.Loading,\n            viewModel.uiState.value\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel starts with Loading state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The test checks the initial value before the scheduled repository operation completes.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">24. Test Successful Product Loading<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `products load successfully`() = runTest {\n\n    val repository = FakeProductRepository()\n\n    val viewModel = ProductViewModel(repository)\n\n    advanceUntilIdle()\n\n    val state = viewModel.uiState.value\n\n    assertTrue(\n        state is ProductUiState.Success\n    )\n\n    val success = state as ProductUiState.Success\n\n    assertEquals(\n        2,\n        success.products.size\n    )\n\n    assertEquals(\n        \"Android Phone\",\n        success.products.first().name\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">advanceUntilIdle() executes scheduled coroutine work.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The fake repository returns two products.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel publishes Success.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The test verifies the resulting data.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">25. Test Failed Product Loading<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `repository failure produces error state`() = runTest {\n\n    val repository = FakeProductRepository().apply {\n        shouldFail = true\n    }\n\n    val viewModel = ProductViewModel(repository)\n\n    advanceUntilIdle()\n\n    val state = viewModel.uiState.value\n\n    assertTrue(\n        state is ProductUiState.Error\n    )\n\n    val error = state as ProductUiState.Error\n\n    assertEquals(\n        \"Unable to load products\",\n        error.message\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The fake repository throws IOException.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel catches the exception.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The UI state becomes Error.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The test verifies the expected error message.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">26. Test Manual Retry<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s verify that the ViewModel can recover after a failure.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `retry loads products after failure`() = runTest {\n\n    val repository = FakeProductRepository().apply {\n        shouldFail = true\n    }\n\n    val viewModel = ProductViewModel(repository)\n\n    advanceUntilIdle()\n\n    assertTrue(\n        viewModel.uiState.value is ProductUiState.Error\n    )\n\n    repository.shouldFail = false\n\n    viewModel.loadProducts()\n\n    advanceUntilIdle()\n\n    assertTrue(\n        viewModel.uiState.value is ProductUiState.Success\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The first request fails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The repository is then configured to succeed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel retries loading.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The final state becomes Success.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This verifies recovery behavior.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">27. Test ViewModel StateFlow with Turbine<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s verify the complete loading-to-success sequence.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `viewmodel emits loading then success`() = runTest {\n\n    val repository = FakeProductRepository()\n\n    val viewModel = ProductViewModel(repository)\n\n    viewModel.uiState.test {\n\n        assertEquals(\n            ProductUiState.Loading,\n            awaitItem()\n        )\n\n        advanceUntilIdle()\n\n        val success = awaitItem()\n\n        assertTrue(\n            success is ProductUiState.Success\n        )\n\n        cancelAndIgnoreRemainingEvents()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The test first observes Loading.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The scheduler then executes the repository request.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel publishes Success.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Turbine verifies the state transition.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The test starts collecting before advancing the scheduler.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This helps prevent the collector from missing meaningful intermediate states.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">28. Test ViewModel Error State with Turbine<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\nfun `viewmodel emits loading then error`() = runTest {\n\n    val repository = FakeProductRepository().apply {\n        shouldFail = true\n    }\n\n    val viewModel = ProductViewModel(repository)\n\n    viewModel.uiState.test {\n\n        assertEquals(\n            ProductUiState.Loading,\n            awaitItem()\n        )\n\n        advanceUntilIdle()\n\n        val error = awaitItem()\n\n        assertTrue(\n            error is ProductUiState.Error\n        )\n\n        cancelAndIgnoreRemainingEvents()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The test verifies that the ViewModel transitions from Loading to Error when the repository fails.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">29. Recommended Project Structure<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Organize production and test code clearly.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>app\/\n\u2502\n\u251c\u2500\u2500 src\/\n\u2502   \u251c\u2500\u2500 main\/\n\u2502   \u2502   \u2514\u2500\u2500 java\/com\/example\/app\/\n\u2502   \u2502       \u2502\n\u2502   \u2502       \u251c\u2500\u2500 data\/\n\u2502   \u2502       \u2502   \u2514\u2500\u2500 ProductRepository.kt\n\u2502   \u2502       \u2502\n\u2502   \u2502       \u251c\u2500\u2500 model\/\n\u2502   \u2502       \u2502   \u2514\u2500\u2500 Product.kt\n\u2502   \u2502       \u2502\n\u2502   \u2502       \u2514\u2500\u2500 ui\/\n\u2502   \u2502           \u251c\u2500\u2500 ProductUiState.kt\n\u2502   \u2502           \u2514\u2500\u2500 ProductViewModel.kt\n\u2502   \u2502\n\u2502   \u2514\u2500\u2500 test\/\n\u2502       \u2514\u2500\u2500 java\/com\/example\/app\/\n\u2502           \u2502\n\u2502           \u251c\u2500\u2500 MainDispatcherRule.kt\n\u2502           \u2502\n\u2502           \u251c\u2500\u2500 FakeProductRepository.kt\n\u2502           \u2502\n\u2502           \u2514\u2500\u2500 ProductViewModelTest.kt<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Production code belongs in the main source set.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Local JVM tests belong in the test source set.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Fake repositories and test rules can be reused across multiple tests.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">30. Common Kotlin Flow Testing Mistakes<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 1: Using runBlocking Instead of runTest<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">runBlocking can execute coroutine code but does not provide the same virtual-time testing utilities.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Prefer runTest for coroutine unit tests.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 2: Using Real Delays<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid unnecessary real-time waiting in unit tests.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use virtual time when possible.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 3: Forgetting to Replace Dispatchers.Main<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">ViewModel tests using viewModelScope may fail without a test Main dispatcher.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 4: Using Different Test Schedulers<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Test dispatchers should share a scheduler when coordinated virtual-time execution is required.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 5: Collecting StateFlow with toList()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow normally never completes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use direct value assertions or a controlled collector such as Turbine.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 6: Ignoring StateFlow Conflation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StateFlow may skip intermediate values.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not assume every rapid update produces a separately observable emission.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 7: Emitting SharedFlow Events Before Subscribing<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A SharedFlow with replay = 0 does not replay old events to new subscribers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 8: Forgetting to Cancel Infinite Collectors<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Long-lived Flow collectors should be cancelled when the test finishes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 9: Testing Real APIs in Unit Tests<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use fake repositories for isolated ViewModel tests.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Reserve real integration testing for appropriate test environments.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 10: Relying on Uncontrolled Coroutine Ordering<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use StandardTestDispatcher and scheduler controls when precise ordering matters.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">31. Kotlin Flow Testing Best Practices<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Follow these recommendations:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use runTest for coroutine unit tests.<\/li>\n\n\n\n<li>Prefer deterministic virtual-time testing.<\/li>\n\n\n\n<li>Use Turbine for emission-sequence assertions.<\/li>\n\n\n\n<li>Use StateFlow.value for simple state assertions.<\/li>\n\n\n\n<li>Test loading, success, and error states.<\/li>\n\n\n\n<li>Test retry and recovery behavior.<\/li>\n\n\n\n<li>Use fake repositories instead of real network calls.<\/li>\n\n\n\n<li>Inject dispatchers where necessary.<\/li>\n\n\n\n<li>Replace Dispatchers.Main in ViewModel JVM tests.<\/li>\n\n\n\n<li>Keep test dispatchers on the same scheduler.<\/li>\n\n\n\n<li>Cancel long-lived collectors.<\/li>\n\n\n\n<li>Understand StateFlow conflation.<\/li>\n\n\n\n<li>Test SharedFlow subscriber timing.<\/li>\n\n\n\n<li>Avoid unnecessary real delays.<\/li>\n\n\n\n<li>Test both successful and failing operations.<\/li>\n\n\n\n<li>Keep unit tests independent and repeatable.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">32. Kotlin Flow Testing Quick Reference<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>API<\/th><th>Purpose<\/th><\/tr><tr><td>runTest()<\/td><td>Coroutine test scope<\/td><\/tr><tr><td>TestCoroutineScheduler<\/td><td>Controls virtual time<\/td><\/tr><tr><td>StandardTestDispatcher<\/td><td>Queued coroutine execution<\/td><\/tr><tr><td>UnconfinedTestDispatcher<\/td><td>Eager coroutine entry<\/td><\/tr><tr><td>runCurrent()<\/td><td>Run currently scheduled tasks<\/td><\/tr><tr><td>advanceTimeBy()<\/td><td>Advance virtual time<\/td><\/tr><tr><td>advanceUntilIdle()<\/td><td>Run scheduled work until idle<\/td><\/tr><tr><td>Turbine test {}<\/td><td>Collect and verify Flow<\/td><\/tr><tr><td>awaitItem()<\/td><td>Await next emission<\/td><\/tr><tr><td>awaitComplete()<\/td><td>Verify completion<\/td><\/tr><tr><td>awaitError()<\/td><td>Verify failure<\/td><\/tr><tr><td>cancelAndIgnoreRemainingEvents()<\/td><td>Cancel infinite collection<\/td><\/tr><tr><td>Dispatchers.setMain()<\/td><td>Replace Main dispatcher<\/td><\/tr><tr><td>Dispatchers.resetMain()<\/td><td>Restore Main dispatcher<\/td><\/tr><tr><td>StateFlow.value<\/td><td>Read current state<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">33. Practical Exercises<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Try these exercises to strengthen your understanding.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 1: Basic Flow Test<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a Flow that emits five integers and verify them using toList().<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 2: Turbine Test<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use Turbine to verify three String emissions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 3: Error Test<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a Flow that throws IllegalStateException and verify it using awaitError().<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 4: StateFlow Test<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a counter StateFlow and verify increment and reset behavior.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 5: SharedFlow Test<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a SharedFlow event producer and verify an emitted message.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 6: Virtual Time<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Create a coroutine with delay(5000) and test it using advanceTimeBy().<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 7: debounce Test<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Test a search query Flow using debounce(300).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 8: retryWhen Test<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Verify that a Flow succeeds after two temporary failures.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 9: ViewModel Error Test<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use a fake repository to verify a ViewModel error state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exercise 10: Complete ViewModel Test<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Implement the complete ProductViewModel testing mini-project from this tutorial.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">34. Frequently Asked Questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is Kotlin Flow testing?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Kotlin Flow testing verifies the values, state transitions, errors, and asynchronous behavior of Flow-based code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is Turbine?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Turbine is a library that simplifies testing Kotlin Flow emissions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is runTest()?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">runTest() is a coroutine testing function that provides controlled execution and virtual-time support.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is StandardTestDispatcher?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">StandardTestDispatcher queues coroutine execution under a test scheduler.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is UnconfinedTestDispatcher?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">UnconfinedTestDispatcher eagerly enters launched coroutines and is useful for certain collection scenarios.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I test StateFlow?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You can verify StateFlow.value or collect emissions using Turbine.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I test SharedFlow?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Start collecting before emitting values, then verify received events.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why should I use fake repositories?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Fake repositories allow tests to simulate success and failure without relying on real APIs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I test ViewModel coroutines?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Replace Dispatchers.Main with a test dispatcher and use runTest to control coroutine execution.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I test debounce without waiting?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Use virtual time with TestCoroutineScheduler.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should I use runBlocking or runTest?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For coroutine unit testing, runTest is generally preferred because it provides test scheduling and virtual-time capabilities.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What We&#8217;ve Learned<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we learned:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Kotlin Flow testing fundamentals<\/li>\n\n\n\n<li>kotlinx-coroutines-test<\/li>\n\n\n\n<li>runTest<\/li>\n\n\n\n<li>TestCoroutineScheduler<\/li>\n\n\n\n<li>StandardTestDispatcher<\/li>\n\n\n\n<li>UnconfinedTestDispatcher<\/li>\n\n\n\n<li>Turbine<\/li>\n\n\n\n<li>Testing cold Flows<\/li>\n\n\n\n<li>Testing StateFlow<\/li>\n\n\n\n<li>Testing SharedFlow<\/li>\n\n\n\n<li>Testing Flow operators<\/li>\n\n\n\n<li>Testing debounce<\/li>\n\n\n\n<li>Testing retryWhen<\/li>\n\n\n\n<li>Testing ViewModel<\/li>\n\n\n\n<li>Replacing Dispatchers.Main<\/li>\n\n\n\n<li>Fake repositories<\/li>\n\n\n\n<li>Loading, success, and error state tests<\/li>\n\n\n\n<li>Common mistakes and best practices<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Testing asynchronous code is essential for building reliable Android applications.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By combining Kotlin Flow, Turbine, runTest, and TestDispatchers, developers can create fast, deterministic, and maintainable unit tests.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These techniques are especially valuable in modern Android projects using ViewModel, MVVM, Kotlin Coroutines, StateFlow, and Jetpack Compose.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In our next tutorial, we&#8217;ll explore:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Kotlin Coroutines &amp; Flow Best Practices in Android: Structured Concurrency, Cancellation &amp; Performance<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ll learn:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Structured concurrency principles<\/li>\n\n\n\n<li>CoroutineScope ownership<\/li>\n\n\n\n<li>viewModelScope and lifecycleScope<\/li>\n\n\n\n<li>Coroutine cancellation<\/li>\n\n\n\n<li>SupervisorJob and exception isolation<\/li>\n\n\n\n<li>Dispatcher selection<\/li>\n\n\n\n<li>Flow performance optimization<\/li>\n\n\n\n<li>Avoiding coroutine leaks<\/li>\n\n\n\n<li>Production architecture patterns<\/li>\n\n\n\n<li>Common coroutine anti-patterns<\/li>\n\n\n\n<li>Practical Android examples<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Happy Coding!<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Continue learning modern Android development with <strong>Moiks Developer Blog<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Master Kotlin Flow testing in Android with Turbine, runTest, StandardTestDispatcher, UnconfinedTestDispatcher, virtual time, StateFlow, SharedFlow, and practical ViewModel unit tests.<\/p>\n","protected":false},"author":1,"featured_media":170,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":2,"footnotes":""},"categories":[3,333,7],"tags":[],"class_list":["post-169","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-android-development","category-android-tutorials","category-coroutines-flow"],"_links":{"self":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/169","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/comments?post=169"}],"version-history":[{"count":1,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/169\/revisions"}],"predecessor-version":[{"id":171,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/169\/revisions\/171"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media\/170"}],"wp:attachment":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media?parent=169"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/categories?post=169"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/tags?post=169"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}