0
0
Kotlinprogramming~10 mins

Testing coroutines with runTest in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to start a coroutine test using runTest.

Kotlin
import kotlinx.coroutines.test.runTest

fun main() = runTest([1]) {
    // test code here
}
Drag options to blanks, or click blank then click option'
A(
B{
C[
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using curly braces directly after runTest without parentheses causes a syntax error.
2fill in blank
medium

Complete the code to launch a coroutine inside runTest.

Kotlin
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.launch

fun main() = runTest {
    val job = [1] {
        // coroutine work
    }
}
Drag options to blanks, or click blank then click option'
Alaunch
Basync
CrunBlocking
Ddelay
Attempts:
3 left
💡 Hint
Common Mistakes
Using async instead of launch when no result is needed.
Using runBlocking inside runTest causes blocking issues.
3fill in blank
hard

Fix the error in the test code by completing the runTest call correctly.

Kotlin
import kotlinx.coroutines.test.runTest

fun testSomething() = runTest([1]) {
    // test logic
}
Drag options to blanks, or click blank then click option'
A[
B{
C(
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using curly braces directly after runTest without parentheses.
4fill in blank
hard

Complete the code to correctly create a test coroutine that delays and asserts a value.

Kotlin
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.delay
import kotlin.test.assertEquals

fun main() = runTest() {
    delay(100)
    val result = 5
    assertEquals([1], result)
}
Drag options to blanks, or click blank then click option'
A(
B5
C10
D{
Attempts:
3 left
💡 Hint
Common Mistakes
Using curly braces instead of parentheses for runTest.
Using wrong expected value in assertEquals.
5fill in blank
hard

Fill both blanks to create a test that launches a coroutine, delays, and cancels the job.

Kotlin
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay

fun main() = runTest() {
    val job = [1] {
        delay(1000)
    }
    [2].cancel()
}
Drag options to blanks, or click blank then click option'
A(
Blaunch
Cjob
D{
Attempts:
3 left
💡 Hint
Common Mistakes
Using curly braces instead of parentheses for runTest.
Using wrong variable name instead of job to cancel.