Search⌘ K
AI Features

Testing Functions Properties

Explore how to test Kotlin coroutine functions by manipulating virtual time and using the StandardTestDispatcher. Learn techniques for checking state changes during execution, testing coroutines that launch other coroutines, and replacing the main dispatcher in unit tests to prevent errors. This lesson helps you understand precise coroutine testing methods including time control functions and dispatcher management.

Testing what happens during function execution

Imagine a function that, during its execution, first shows a progress bar and then later hides it.

Kotlin 1.5
suspend fun sendUserData() {
val userData = database.getUserData()
progressBarVisible.value = true
userRepository.sendUserData(userData)
progressBarVisible.value = false
}

If we only check the final result, we cannot verify that the progress bar changed its state during function execution. A helpful trick in such cases is to start this function in a new coroutine and control virtual time from outside. Notice that runTest creates a coroutine with the StandardTestDispatcher dispatcher and advances its time until idle (using the advanceUntilIdle function). This means that the children’s time will start ...