CodeBlanks Logo Icon CodeBlanks

Summary - Advanced testing

Combine runTest, Turbine and MockK to write a ViewModel test.

Summary - Advanced testing

In this group you saw the advanced testing tools: runTest for coroutines, Turbine for Flows, MockK for mocking, Testcontainers for real containers and kotest-property for property tests.

This lesson includes a small task that combines three of them: you will write a test that calls fetchUser inside runTest and prints the result. This pattern is the foundation of advanced Kotlin testing.

Practice Summary: write the fetchUser test

Define a suspend function fetchUser(id: Int): String that returns "Alex" when id is 1. In main open a runTest block; assign the result of fetchUser(1) to a variable, assert it with assertEquals("Alex", result) and print println(result).

Starter code

Main.kt
import kotlinx.coroutines.test.runTest

// suspend function: returns Alex for id=1
// open runTest block in main; assert and print fetchUser(1)

Sample solution

Main.kt
import kotlinx.coroutines.test.runTest
import kotlin.test.assertEquals

suspend fun fetchUser(id: Int): String {
    return "Alex"
}

fun main() = runTest {
    val result = fetchUser(1)
    assertEquals("Alex", result)
    println(result)
}

Expected output

Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which builder is used to test a suspend function?

  • Thread.sleep
  • runBlocking
  • runTest Correct answer
  • Thread.start

Explanation: runTest opens a TestScope for suspend functions.

2 Complete the Turbine test block

Question
scoreFlow().____ {
    println(awaitItem())
    awaitComplete()
}
Answer
scoreFlow().test {
    println(awaitItem())
    awaitComplete()
}

Explanation: scoreFlow().test opens a Turbine subscription.

3 Match the testing tools

Term Meaning
runTest Coroutine test
Turbine Flow test
MockK Mocking
kotest-property Property test

All lessons in Advanced