0
0
Kotlinprogramming~10 mins

Kotlin test assertions - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Kotlin test assertions
Write test function
Call function to test
Use assertion to check result
Assertion passes?
NoTest fails, show error
Yes
Test passes, continue or finish
This flow shows how a Kotlin test calls a function, checks the result with assertions, and passes or fails the test.
Execution Sample
Kotlin
fun add(a: Int, b: Int) = a + b

fun testAdd() {
    val result = add(2, 3)
    assert(result == 5) { "Expected 5 but got $result" }
}
This code tests the add function by asserting the result equals 5.
Execution Table
StepActionEvaluationResult
1Call add(2, 3)2 + 35
2Store resultresult = 55
3Assert result == 55 == 5True, assertion passes
4Test endsNo errorsTest passes
💡 Assertion passes because result equals expected value 5
Variable Tracker
VariableStartAfter Step 1After Step 2Final
resultundefined555
Key Moments - 2 Insights
Why does the test fail if the assertion condition is false?
Because the assertion throws an error stopping the test, as shown in the execution_table step 3 where a false condition would cause failure.
What does the message inside assert { } do?
It shows a clear error message if the assertion fails, helping to understand what went wrong, as seen in the code sample.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'result' after step 2?
A5
B3
Cundefined
D0
💡 Hint
Check the 'Store result' row in the execution_table where result is set to 5.
At which step does the assertion check happen?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Assert result == 5' action in the execution_table.
If the add function returned 4 instead of 5, what would happen at step 3?
AResult changes to 5
BAssertion passes
CAssertion fails and test stops
DTest continues without error
💡 Hint
Refer to key_moments about assertion failure stopping the test.
Concept Snapshot
Kotlin test assertions check if a condition is true.
Use assert(condition) { "message" } inside test functions.
If condition is false, test fails with the message.
Assertions help verify code works as expected.
They stop the test immediately on failure.
Full Transcript
This visual trace shows how Kotlin test assertions work. First, a test function calls the function to test. The result is stored in a variable. Then an assertion checks if the result matches the expected value. If true, the test passes and continues. If false, the assertion throws an error and the test fails immediately. The message inside the assertion helps explain the failure. Variables like 'result' change as the test runs. Understanding these steps helps beginners see how tests verify code correctness.