Search code examples
javaunit-testingjunitwhile-loopcode-coverage

Constructing loop coverage for nested conditional loops in Java


I am currently learning about code coverage testing, specifically loop coverage, in Java. From context, loop coverage involves running a loop 0, 1 and >1 times. However, I've encountered a problem with a specific function structure that I'm trying to test.

The structure is as follows:

function() {
    if(A){
        //do something here as well

        while(A){
            //do something
        }
    }
}

The while loop is nested within an if statement, both of which have the exact same condition A. This structure seems to prevent me from creating a test case where the while loop would execute zero times since the enclosing if statement will prevent entering the loop if A is false.

Given this structure, how can I construct test cases that provide loop coverage (0, 1, >1 iterations) for the while loop?


Solution

  • Let's assume you have a statement (or several statements) that change the value of A inside the loop, otherwise, once entered, it would be an infinite loop.

    Two of these cases are easy:
    For 1, you need a value of A that's true, and some additional conditions that cause A to become false in the first iteration.
    For >1, you need a value of A that's true, and some additional conditions that make sure A remains true in the first iteration of the loop, but presumably becomes false some time later.

    For the coverage of 0, in the sense that the loop's condition is evaluated but never entered, you have a problem. Assuming the "do something here as well" under the if does not change the value of A, there is simply no way to evaluate the loop condition but not enter it. This situation would require A to be false, but if it is, the loop won't even be reached.