Testing Kotlin Coroutines: runTest, TestScheduler, and Turbine for Flows

Testing Kotlin Coroutines: runTest, TestScheduler, and Turbine for Flows

Testing asynchronous Kotlin coroutines requires specialized tools: runTest for structured concurrency, TestCoroutineScheduler for time manipulation, and Turbine for Flow assertions. This guide shows you exactly how to use each one with real examples.

Coroutines are the reason most Kotlin codebases are fast and readable. But testing asynchronous code has a reputation for being painful. The kotlinx-coroutines-test library, combined with Turbine for Flows, eliminates most of that pain. Once you understand the mental model, coroutine tests are as straightforward as synchronous ones.

Setup

dependencies {
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.8.1")
    testImplementation("app.cash.turbine:turbine:1.1.0")
    testImplementation("io.mockk:mockk:1.13.11")
}

The Mental Model: Virtual Time

The key insight is that runTest uses a TestCoroutineScheduler that controls time. When you call delay(5000) inside a runTest block, that delay does not actually wait 5 seconds. The scheduler advances virtual time instantly. Your tests run in milliseconds even if the production code has long delays.

@Test
fun `delayed operation completes instantly in tests`() = runTest {
    var result = ""

    launch {
        delay(10_000) // 10 second delay in production
        result = "done"
    }

    advanceTimeBy(10_001)
    result shouldBe "done"
    // This test runs in ~1ms, not 10 seconds
}

runTest Basics

runTest is the entry point for all coroutine tests. It:

  • Provides a TestScope with virtual time
  • Automatically advances time past all pending delays when the test body exits
  • Fails on uncaught exceptions from child coroutines
  • Ensures all coroutines complete before the test ends
class TimerServiceTest {

    private val service = TimerService()

    @Test
    fun `timer fires callback after delay`() = runTest {
        var fired = false

        service.scheduleAfter(delayMs = 5000) {
            fired = true
        }

        assertFalse(fired) // Not yet
        advanceTimeBy(5001)
        assertTrue(fired) // Fired after delay
    }

    @Test
    fun `timer can be cancelled before firing`() = runTest {
        var fired = false
        val timer = service.scheduleAfter(delayMs = 5000) { fired = true }

        advanceTimeBy(2000)
        timer.cancel()
        advanceTimeBy(5000) // Past original deadline

        assertFalse(fired) // Never fired because we cancelled
    }
}

Injecting TestDispatcher

Production code should never hardcode Dispatchers.IO or Dispatchers.Default inside a class. Instead, inject the dispatcher so tests can substitute a TestDispatcher.

// Production class — takes dispatcher as constructor parameter
class UserRepository(
    private val db: Database,
    private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) {
    suspend fun loadUser(id: Int): User = withContext(dispatcher) {
        db.query("SELECT * FROM users WHERE id = ?", id)
    }
}

In tests, inject UnconfinedTestDispatcher or StandardTestDispatcher:

class UserRepositoryTest {

    private val testDispatcher = StandardTestDispatcher()
    private val db = mockk<Database>()
    private lateinit var repo: UserRepository

    @BeforeEach
    fun setUp() {
        repo = UserRepository(db, testDispatcher)
    }

    @Test
    fun `loadUser queries database with correct id`() = runTest(testDispatcher) {
        val user = User(id = 1, name = "Alice")
        coEvery { db.query(any(), 1) } returns user

        val result = repo.loadUser(1)

        result shouldBe user
        coVerify { db.query(any(), 1) }
    }
}

StandardTestDispatcher vs UnconfinedTestDispatcher

This distinction trips up many developers:

  • StandardTestDispatcher: Coroutines do NOT run until you explicitly advance time. You are in full control of execution order.
  • UnconfinedTestDispatcher: Coroutines run eagerly, executing synchronously until they hit a suspension point.
@Test
fun `standard dispatcher — manual advancement required`() = runTest {
    val dispatcher = StandardTestDispatcher(testScheduler)
    var count = 0

    CoroutineScope(dispatcher).launch {
        count++
    }

    assertEquals(0, count) // Not run yet!
    advanceUntilIdle()
    assertEquals(1, count) // Now it ran
}

@Test
fun `unconstrained dispatcher — runs immediately`() = runTest {
    val dispatcher = UnconfinedTestDispatcher(testScheduler)
    var count = 0

    CoroutineScope(dispatcher).launch {
        count++
    }

    assertEquals(1, count) // Already ran!
}

Use StandardTestDispatcher when testing code where ordering matters. Use UnconfinedTestDispatcher for simpler cases where you just want things to complete without managing advancement.

TestCoroutineScheduler: Precise Time Control

TestCoroutineScheduler is available via testScheduler inside a runTest block.

@Test
fun `retry with exponential backoff`() = runTest {
    var attemptCount = 0
    val service = mockk<ApiService>()

    coEvery { service.fetchData() } coAnswers {
        attemptCount++
        if (attemptCount < 3) throw IOException("Network error")
        else DataResult.Success("data")
    }

    val retryService = RetryService(service, baseDelayMs = 1000)

    // Start the retry operation
    val deferred = async { retryService.fetchWithRetry() }

    // First attempt: immediate
    advanceUntilIdle()
    assertEquals(1, attemptCount)

    // Second attempt: after 1s backoff
    advanceTimeBy(1001)
    advanceUntilIdle()
    assertEquals(2, attemptCount)

    // Third attempt: after 2s backoff (exponential)
    advanceTimeBy(2001)
    advanceUntilIdle()
    assertEquals(3, attemptCount)

    val result = deferred.await()
    result shouldBe DataResult.Success("data")
}

Key time manipulation functions:

  • advanceTimeBy(ms) — moves virtual time forward by ms milliseconds, running any coroutines whose delays expire in that window
  • advanceUntilIdle() — runs all pending coroutines until there is nothing left to run
  • runCurrent() — only runs coroutines that are currently ready, without advancing time
  • currentTime — reads the current virtual clock value

Testing StateFlow and SharedFlow

class SearchViewModelTest {

    private val testDispatcher = UnconfinedTestDispatcher()
    private val searchRepo = mockk<SearchRepository>()
    private lateinit var viewModel: SearchViewModel

    @BeforeEach
    fun setUp() {
        Dispatchers.setMain(testDispatcher)
        viewModel = SearchViewModel(searchRepo)
    }

    @AfterEach
    fun tearDown() {
        Dispatchers.resetMain()
    }

    @Test
    fun `search results update StateFlow`() = runTest {
        val results = listOf(SearchResult("Kotlin testing"), SearchResult("MockK guide"))
        coEvery { searchRepo.search("kotlin") } returns results

        viewModel.search("kotlin")

        viewModel.searchResults.value shouldBe results
    }

    @Test
    fun `loading state is true during search`() = runTest {
        val dispatcher = StandardTestDispatcher(testScheduler)
        Dispatchers.setMain(dispatcher)

        coEvery { searchRepo.search(any()) } coAnswers {
            delay(1000)
            emptyList()
        }

        viewModel.search("kotlin")

        // Before advancing — should be loading
        assertTrue(viewModel.isLoading.value)

        advanceUntilIdle()

        // After completion — should not be loading
        assertFalse(viewModel.isLoading.value)
    }
}

Turbine: Testing Flows

Turbine is a testing library specifically for Kotlin Flows. It turns Flow consumption into a sequential, assertion-friendly API.

// Production code
class MessageService(private val repo: MessageRepository) {
    fun observeMessages(channelId: String): Flow<List<Message>> =
        repo.getMessages(channelId)
            .map { it.sortedByDescending { msg -> msg.timestamp } }
            .distinctUntilChanged()
}
class MessageServiceTest {

    val repo = mockk<MessageRepository>()
    val service = MessageService(repo)

    @Test
    fun `messages are sorted by timestamp descending`() = runTest {
        val messages = MutableSharedFlow<List<Message>>()
        every { repo.getMessages("ch-1") } returns messages

        service.observeMessages("ch-1").test {
            messages.emit(listOf(
                Message(id = 1, text = "Hello", timestamp = 1000),
                Message(id = 2, text = "World", timestamp = 2000)
            ))

            val received = awaitItem()
            received[0].id shouldBe 2 // Most recent first
            received[1].id shouldBe 1

            cancelAndIgnoreRemainingEvents()
        }
    }

    @Test
    fun `identical emissions are deduplicated`() = runTest {
        val messages = MutableSharedFlow<List<Message>>()
        every { repo.getMessages("ch-1") } returns messages

        val msg = Message(id = 1, text = "Hello", timestamp = 1000)

        service.observeMessages("ch-1").test {
            messages.emit(listOf(msg))
            awaitItem() // First emission

            messages.emit(listOf(msg)) // Same list
            // No second item should arrive because of distinctUntilChanged

            messages.emit(listOf(msg.copy(text = "Updated")))
            val updated = awaitItem()
            updated[0].text shouldBe "Updated"

            cancelAndIgnoreRemainingEvents()
        }
    }
}

Turbine Error Testing

@Test
fun `flow emits error when repository fails`() = runTest {
    every { repo.getMessages("ch-1") } returns flow {
        emit(emptyList<Message>())
        throw IOException("Connection lost")
    }

    service.observeMessages("ch-1").test {
        awaitItem() // Initial empty list
        val error = awaitError()
        error.shouldBeInstanceOf<IOException>()
        error.message shouldBe "Connection lost"
    }
}

Testing Complete Flows

@Test
fun `paginated loader emits all pages then completes`() = runTest {
    every { repo.getPage(any()) } answers {
        val page = firstArg<Int>()
        if (page < 3) flowOf(PageResult(page, hasMore = true))
        else flowOf(PageResult(page, hasMore = false))
    }

    service.loadAllPages().test {
        awaitItem().page shouldBe 1
        awaitItem().page shouldBe 2
        awaitItem().page shouldBe 3
        awaitComplete()
    }
}

Testing Exception Handling in Coroutines

@Test
fun `CoroutineExceptionHandler captures uncaught exceptions`() = runTest {
    var caughtException: Throwable? = null
    val handler = CoroutineExceptionHandler { _, throwable ->
        caughtException = throwable
    }

    val scope = CoroutineScope(testDispatcher + handler)

    scope.launch {
        throw IllegalStateException("Oops")
    }

    advanceUntilIdle()

    caughtException.shouldBeInstanceOf<IllegalStateException>()
    caughtException!!.message shouldBe "Oops"
}

@Test
fun `structured concurrency cancels siblings on child failure`() = runTest {
    var secondJobStarted = false
    var secondJobCompleted = false

    assertThrows<IllegalStateException> {
        coroutineScope {
            launch {
                delay(100)
                throw IllegalStateException("Child failed")
            }

            launch {
                secondJobStarted = true
                delay(500) // Would outlive the failing sibling
                secondJobCompleted = true
            }
        }
    }

    advanceUntilIdle()
    assertTrue(secondJobStarted)
    assertFalse(secondJobCompleted) // Cancelled before completing
}

Android ViewModel Testing Pattern

class ProductViewModelTest {

    @get:Rule
    val mainDispatcherRule = MainDispatcherRule() // Custom rule — see below

    private val repo = mockk<ProductRepository>()
    private lateinit var viewModel: ProductViewModel

    @BeforeEach
    fun setUp() {
        viewModel = ProductViewModel(repo)
    }

    @Test
    fun `loads product on init`() = runTest {
        val product = Product(id = 1, name = "Widget", price = 9.99)
        coEvery { repo.getProduct(1) } returns product

        viewModel.loadProduct(1)
        advanceUntilIdle()

        viewModel.uiState.value shouldBe ProductUiState.Success(product)
    }
}

// Reusable rule for setting Main dispatcher in tests
class MainDispatcherRule(
    private val dispatcher: TestDispatcher = UnconfinedTestDispatcher()
) : TestWatcher() {
    override fun starting(description: Description) {
        Dispatchers.setMain(dispatcher)
    }

    override fun finished(description: Description) {
        Dispatchers.resetMain()
    }
}

Key Takeaways

  • Always inject dispatchers — never hardcode Dispatchers.IO inside a class. Dependency injection is what makes tests fast.
  • runTest handles time automatically — delays don't actually wait; the test scheduler advances virtual time.
  • StandardTestDispatcher for ordering, UnconfinedTestDispatcher for simplicity — the wrong choice makes tests non-deterministic.
  • Use Turbine for any Flow test — test { awaitItem() } is far cleaner than manually collecting into a list.
  • Always call Dispatchers.resetMain() in tearDown — forgetting this causes mysterious failures in tests that run after yours.
  • advanceUntilIdle() is your most-used tool — it runs all pending work and is safe to call multiple times.

Read more

Start now free