0
0
Swiftprogramming~5 mins

Test doubles (mocks, stubs) in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Test doubles (mocks, stubs)
O(n)
Understanding Time Complexity

When using test doubles like mocks and stubs, it's important to understand how their use affects the time your tests take to run.

We want to see how the test execution time grows as the number of test doubles or interactions increases.

Scenario Under Consideration

Analyze the time complexity of the following Swift test code using mocks and stubs.


class ServiceMock {
    var callCount = 0
    func fetchData() -> String {
        callCount += 1
        return "mock data"
    }
}

func testService(n: Int) {
    let mock = ServiceMock()
    for _ in 0..

This code simulates calling a mocked service method multiple times in a test.

Identify Repeating Operations
  • Primary operation: Calling fetchData() on the mock object.
  • How many times: Exactly n times, controlled by the loop.
How Execution Grows With Input

Each call to the mock method happens once per loop iteration, so total calls grow directly with n.

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

Pattern observation: The number of operations grows in a straight line as n increases.

Final Time Complexity

Time Complexity: O(n)

This means the test time grows directly in proportion to how many times the mock method is called.

Common Mistake

[X] Wrong: "Using mocks makes tests run instantly, no matter how many calls happen."

[OK] Correct: Each call to a mock method still takes time, so more calls mean longer test runs.

Interview Connect

Understanding how test doubles affect test speed helps you write efficient tests and shows you think about code quality beyond just correctness.

Self-Check

What if the mock method itself called another mock inside it? How would that affect the time complexity?