Writing basic test functions in Go - Time & Space Complexity
When writing basic test functions in Go, it is important to understand how the time taken grows as tests run on more cases.
We want to know how the number of tests affects the total time to complete all tests.
Analyze the time complexity of the following code snippet.
func TestSum(t *testing.T) {
for i := 0; i < len(testCases); i++ {
got := Sum(testCases[i].input)
if got != testCases[i].expected {
t.Errorf("Sum() = %d; want %d", got, testCases[i].expected)
}
}
}
This test function runs through a list of test cases and checks if the Sum function returns the expected result for each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each test case once.
- How many times: Exactly once per test case in the list.
As the number of test cases grows, the total time grows in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: Doubling the number of test cases roughly doubles the total work done.
Time Complexity: O(n)
This means the time to run all tests grows linearly with the number of test cases.
[X] Wrong: "Running more tests won't affect total time much because each test is small."
[OK] Correct: Even small tests add up, so more tests mean more total time in a straight line.
Understanding how test functions scale helps you write efficient tests and reason about testing time in real projects.
What if we added nested loops inside each test case? How would the time complexity change?