Consider this Kotlin function that tests if a number is even. What will be printed when this test runs?
fun isEven(n: Int) = n % 2 == 0 fun testIsEven() { val testNumber = 4 if (isEven(testNumber)) { println("Test passed") } else { println("Test failed") } } testIsEven()
Think about what the function isEven returns for 4.
The number 4 is even, so isEven(4) returns true. The test prints "Test passed".
Which of the following is the main reason programmers write tests for their code?
Think about what testing helps prevent before the program is used.
Tests help find mistakes early and ensure the program behaves correctly.
Look at this Kotlin test code. What error will it cause when run?
fun divide(a: Int, b: Int): Int = a / b fun testDivide() { val result = divide(10, 0) println("Result is $result") } testDivide()
What happens if you divide a number by zero in Kotlin?
Dividing by zero causes an ArithmeticException at runtime.
Given this Kotlin test suite, how many tests will be executed?
fun testAdd() { println("Add test") } fun testSubtract() { println("Subtract test") } fun testMultiply() { println("Multiply test") } fun runTests() { testAdd() testSubtract() } runTests()
Look at which test functions are called inside runTests().
Only testAdd and testSubtract are called, so 2 tests run.
Consider this Kotlin code that tests if numbers are positive. What is the value of the variable passed after running runTests()?
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()
Count how many numbers in the list are greater than zero.
Only 1 and 5 are positive, so passed increments twice.