I have generated the program graph of a method that contains an if condition and a for loop, and I need to generate test cases that covers "every branch". Would this include the for loop, given that program graphs are abstractions of the actual code, and the for loop does cause there to be two separate paths in the program graph?

public int void randMethod(int num) {
    for (i = 0; i <= 1; i++) {
        if (num == 1) {
        } else {

Could you cover all branches with a single test case, i.e. where the num input == 1?

1 Answer 1


Yes, why would it not?

Note that the for loop case is often a triviality, you just make sure that one of your test cases is such that the loop executes at least once and terminates, job done.

The same thing applies to a while loop and to any other loop type constructs you may have.

  • In that case, wouldn't you also need a test case where the loop doesn't execute at all? Jun 3, 2018 at 18:04
  • 1
    Not really, for the purpose of coverage of the control flow paths, a single iteration or more that terminates tests both branches of the condition. Consider something like for (x=0; x < y; x++) {....}; If ye can test for a non zero y, say 1 for example then on the first pass x=0, so the branch causes the loop to execute the body and increment x, on the next pass x = 1, so the loop exits.... Thus both code paths are covered. Now there might be a unit testing argument for the does not execute at all case but that is a different question (And maybe also for the 'loop does not terminate' case!).
    – Dan Mills
    Jun 3, 2018 at 18:18
  • I appreciate the explanation. Could I just clarify one last thing? If we have the code (please see edit of the original question), and we want to test all branches (so the case where the if executes, and the case where the else executes, can we achieve this with a single test case as it's in a loop? (so during one iteration of the loop the if runs, and during the next iteration the else runs, is that considered to have covered all the branches, even though it's in a single test case? Jun 3, 2018 at 18:37
  • From a code coverage perspective that would exercise all the code, but is is probably a poor test as you should also probably aim to test the other case of the input variable where num is not equal to 1 and this only some of the code in the loop runs... This is however not a code coverage question in the strict sense but would be something I would flag at review. Note that automatically detecting such things falls into the whole question of computability and 'does it halt' and are thus in the general case not really easily amenable to automated analysis.
    – Dan Mills
    Jun 3, 2018 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.