Mocking with MockK in Kotlin - Time & Space Complexity
When using MockK to create mocks in Kotlin tests, it's helpful to understand how the time to run tests grows as mocks and calls increase.
We want to see how the number of mocked calls affects the test execution time.
Analyze the time complexity of this simple mocking setup and verification.
import io.mockk.mockk
import io.mockk.verify
fun testMockCalls(n: Int) {
val mock = mockk>()
for (i in 1..n) {
verify(exactly = 0) { mock[i] }
}
}
This code creates a mock list and verifies calls to its get method n times.
Look at what repeats as input grows.
- Primary operation: The for-loop runs verify n times.
- How many times: Exactly n times, once per loop iteration.
As n grows, the number of verify calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 verify calls |
| 100 | 100 verify calls |
| 1000 | 1000 verify calls |
Pattern observation: The work grows directly with n, so doubling n doubles the operations.
Time Complexity: O(n)
This means the time to run the test grows in a straight line as the number of mocked calls increases.
[X] Wrong: "Mocking and verifying calls always take constant time no matter how many calls there are."
[OK] Correct: Each verify call checks the mock's history, so more calls mean more work, making time grow with n.
Understanding how mocking affects test time helps you write efficient tests and shows you know how code scales, a useful skill in real projects.
"What if we verified all calls once after the loop instead of inside it? How would the time complexity change?"