0
0
Kotlinprogramming~5 mins

Mocking with MockK in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Mocking with MockK
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As n grows, the number of verify calls grows the same way.

Input Size (n)Approx. Operations
1010 verify calls
100100 verify calls
10001000 verify calls

Pattern observation: The work grows directly with n, so doubling n doubles the operations.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the test grows in a straight line as the number of mocked calls increases.

Common Mistake

[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.

Interview Connect

Understanding how mocking affects test time helps you write efficient tests and shows you know how code scales, a useful skill in real projects.

Self-Check

"What if we verified all calls once after the loop instead of inside it? How would the time complexity change?"