Definition
Loop Coverage
Loop coverage is a structural testing metric designed to test the validity of loop structures. It ensures that every loop is executed 0 times, 1 time, and >1 times.
Concept
Simple metrics like statement or branch coverage often test loops only once (the “standard” pass). Loop coverage specifically targets boundary conditions related to iteration logic.
Required Test Cases
For a simple loop while (C) { ... }:
- Zero Iterations: The loop condition C is initially false. The body is skipped entirely.
- Goal: Verify code behaviour when the loop is bypassed (e.g., handling empty input arrays).
- One Iteration: The loop body runs exactly once, then C becomes false.
- Goal: Verify basic “execute once” logic.
- Multiple Iterations: The loop body runs more than once (e.g., 2 or “typical” usage).
- Goal: Verify that state updates correctly between iterations (e.g., incrementing counters, moving array pointers).
Lecture Insight: Why >1 matters
In the lecture example (reversing an array), a bug existed where the index pointer
jwas never decremented inside the loop.
- 0 Iterations: Passed (empty array returns empty).
- 1 Iteration: Passed (array of size 1 returns itself;
jdidn’t need to move).- >1 Iterations: Failed. The loop ran twice, but
jpointed to the same spot, overwriting data incorrectly. Only the >1 case revealed the bug.
Example
Consider a simple summation loop:
public int sum(int n) {
int s = 0;
while (n > 0) { // Condition C
s += n;
n--;
}
return s;
}
Coverage Analysis
To achieve 100% Loop Coverage, we need three distinct test inputs:
-
0 Iterations:
n = 0n > 0is false immediately. Body skipped. Returns 0.
-
1 Iteration:
n = 1- Pass 1:
1 > 0(True),s=1, n=0. - Pass 2:
0 > 0(False). Returns 1.
- Pass 1:
-
Multiple Iterations:
n = 2- Pass 1:
2 > 0(True),s=2, n=1. - Pass 2:
1 > 0(True),s=3, n=0. - Pass 3:
0 > 0(False). Returns 3.
- Pass 1: