0
0
Kotlinprogramming~5 mins

Testing coroutines with runTest in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of runTest in Kotlin coroutine testing?

runTest is used to run coroutine code in a controlled test environment. It helps to test suspend functions by providing a special coroutine scope and controlling the virtual time.

Click to reveal answer
intermediate
How does runTest help with timing in coroutine tests?

runTest controls virtual time, allowing you to advance time manually without waiting in real time. This makes tests faster and deterministic.

Click to reveal answer
intermediate
What happens if a coroutine launched inside runTest is not completed by the end of the test?

The test will fail because runTest checks for uncompleted coroutines to avoid leaks and ensure all work is done.

Click to reveal answer
beginner
Show a simple example of using runTest to test a suspend function.
<pre>import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals

class MyTest {
    @Test
    fun testSuspendFunction() = runTest {
        val result = suspendFunction()
        assertEquals("Hello", result)
    }

    suspend fun suspendFunction(): String {
        return "Hello"
    }
}</pre>
Click to reveal answer
intermediate
Why should you avoid using Thread.sleep() inside runTest?

Thread.sleep() blocks the thread and does not advance virtual time in runTest. Instead, use advanceTimeBy() or delay() to simulate time passing.

Click to reveal answer
What does runTest provide when testing coroutines?
AA replacement for <code>Thread.sleep()</code>
BA way to run blocking code only
CAutomatic UI updates
DA controlled coroutine scope with virtual time
Which function should you use inside runTest to simulate time passing?
Await()
BThread.sleep()
CadvanceTimeBy()
Dsleep()
What happens if a coroutine is still running after runTest finishes?
AThe test fails due to unfinished coroutines
BThe test passes anyway
CThe coroutine is cancelled silently
DThe coroutine runs on a new thread
Which annotation is commonly used with runTest in Kotlin tests?
A@RunWith
B@Test
C@CoroutineTest
D@SuspendTest
Why is runTest preferred over runBlocking for coroutine tests?
ABecause <code>runTest</code> controls virtual time and detects leaks
BBecause <code>runBlocking</code> is deprecated
CBecause <code>runTest</code> runs faster on the UI thread
DBecause <code>runBlocking</code> cannot run suspend functions
Explain how runTest helps in testing Kotlin coroutines and why controlling virtual time is important.
Think about how waiting in real time can slow tests and how virtual time solves that.
You got /4 concepts.
    Describe a simple test case using runTest to verify a suspend function returns the expected result.
    Imagine you want to check a function that says 'Hello' after a delay.
    You got /4 concepts.