Kotlin test assertions - Time & Space Complexity
We want to understand how the time it takes to run Kotlin test assertions changes as the number of tests or checks grows.
How does adding more assertions affect the total time to run them all?
Analyze the time complexity of the following code snippet.
fun testSum() {
val numbers = listOf(1, 2, 3, 4, 5)
val result = numbers.sum()
assert(result == 15) { "Sum should be 15" }
}
fun testAll() {
testSum()
testSum()
testSum()
}
This code runs a simple sum test three times, each with one assertion checking the result.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The sum() function loops through the list to add numbers.
- How many times: sum() runs once per testSum call, and testSum is called three times.
As the number of tests or assertions increases, the total work grows proportionally.
| Input Size (number of tests) | Approx. Operations |
|---|---|
| 10 | 10 sums and 10 assertions |
| 100 | 100 sums and 100 assertions |
| 1000 | 1000 sums and 1000 assertions |
Pattern observation: Doubling the number of tests doubles the total operations.
Time Complexity: O(n * m)
This means the time grows with both the number of tests (n) and the size of data each test processes (m).
[X] Wrong: "Assertions run instantly and don't affect time complexity."
[OK] Correct: Each assertion checks a condition, so more assertions mean more checks and more time.
Understanding how test assertions scale helps you write efficient tests and reason about test suite performance in real projects.
"What if each test had multiple assertions instead of one? How would the time complexity change?"