Handling loops and similar constructs

You may wonder what to do in the case of loops, such as for and while. The code block inside the loop may be executed different numbers of times, making testing more complicated.

Think of a while(true) loop, which can be non-terminating. To be rigorous, we would have to test the program with the loop block executed one time, two times, three times, and so on. Or imagine a for(i = 0; i < 10; i++) loop with a break inside the body. We would have to test what happened if the loop body executed up to 10 times. How can we handle a long-lasting loop (that runs for many iterations) or an unbounded loop (that is executed an unknown number of times)?

Given that exhaustive testing is impossible, testers often rely on the loop boundary adequacy criterion to decide when to stop testing a loop. A test suite satisfies this criterion if and only if for every loop

  • There is a test case that exercises the loop zero times.
  • There is a test case that exercises the loop once.
  • There is a test case that exercises the loop multiple times.

Pragmatically speaking, my experience shows that the main challenge comes when devising the test case for the loop being executed multiple times. Should the test case force the loop to iterate 2, 5, or 10 times? This decision requires a good understanding of the program and its requirement. With optimal understanding of the specs, you should be able to devise good tests for the loop. Do not be afraid to create two or more tests for the “multiple times” case. Do whatever you need to do to ensure that the loop works as expected.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *