Test doubles (mocks, stubs) in Swift - Time & Space 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.
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.
- Primary operation: Calling
fetchData()on the mock object. - How many times: Exactly
ntimes, controlled by the loop.
Each call to the mock method happens once per loop iteration, so total calls grow directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to fetchData() |
| 100 | 100 calls to fetchData() |
| 1000 | 1000 calls to fetchData() |
Pattern observation: The number of operations grows in a straight line as n increases.
Time Complexity: O(n)
This means the test time grows directly in proportion to how many times the mock method is called.
[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.
Understanding how test doubles affect test speed helps you write efficient tests and shows you think about code quality beyond just correctness.
What if the mock method itself called another mock inside it? How would that affect the time complexity?