0
0
Kotlinprogramming~20 mins

Why testing matters in Kotlin - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Testing Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Kotlin test function?

Consider this Kotlin function that tests if a number is even. What will be printed when this test runs?

Kotlin
fun isEven(n: Int) = n % 2 == 0

fun testIsEven() {
    val testNumber = 4
    if (isEven(testNumber)) {
        println("Test passed")
    } else {
        println("Test failed")
    }
}

testIsEven()
ATest passed
BTest failed
CCompilation error
DNo output
Attempts:
2 left
💡 Hint

Think about what the function isEven returns for 4.

🧠 Conceptual
intermediate
1:30remaining
Why do we write tests in programming?

Which of the following is the main reason programmers write tests for their code?

ATo make the program look more complex
BTo make the code run faster
CTo check if the code works as expected and catch errors early
DTo avoid writing comments
Attempts:
2 left
💡 Hint

Think about what testing helps prevent before the program is used.

Predict Output
advanced
2:00remaining
What error does this Kotlin test code raise?

Look at this Kotlin test code. What error will it cause when run?

Kotlin
fun divide(a: Int, b: Int): Int = a / b

fun testDivide() {
    val result = divide(10, 0)
    println("Result is $result")
}

testDivide()
ANo error, prints 'Result is 0'
BArithmeticException: / by zero
CCompilation error
DNullPointerException
Attempts:
2 left
💡 Hint

What happens if you divide a number by zero in Kotlin?

🚀 Application
advanced
1:30remaining
How many tests are run in this Kotlin test suite?

Given this Kotlin test suite, how many tests will be executed?

Kotlin
fun testAdd() { println("Add test") }
fun testSubtract() { println("Subtract test") }
fun testMultiply() { println("Multiply test") }

fun runTests() {
    testAdd()
    testSubtract()
}

runTests()
A2
B3
C1
D0
Attempts:
2 left
💡 Hint

Look at which test functions are called inside runTests().

🔧 Debug
expert
2:30remaining
What is the value of 'passed' after running this Kotlin test code?

Consider this Kotlin code that tests if numbers are positive. What is the value of the variable passed after running runTests()?

Kotlin
var passed = 0

fun isPositive(n: Int) = n > 0

fun testPositive(n: Int) {
    if (isPositive(n)) {
        passed += 1
    }
}

fun runTests() {
    val numbers = listOf(1, -1, 0, 5)
    for (num in numbers) {
        testPositive(num)
    }
}

runTests()
A1
B3
C4
D2
Attempts:
2 left
💡 Hint

Count how many numbers in the list are greater than zero.