liveBook · Manning

Branch coverage

As explained in 100 Java Mistakes and How to Avoid Them

Branch coverage is the fraction of control-flow branches exercised by a test suite.

Branch coverage measures whether each control-flow alternative is exercised by a test suite. It can expose untested behavior even when line or instruction coverage reaches 100%. section 3.8

A missing branch in a loop

In a loop that scans for "%d", tests may exercise the c == '%' path repeatedly while never making c == '%' false after reaching the condition. The loop can then fail to advance and run forever. Tests such as "%%%%" and "%%d%%%d" exercise different branches and expose the risk. section 3.8

Use branch coverage to check loop behavior, not merely statement execution:

  • Test zero, one, and more-than-once iterations. section 3.8
  • Inspect missing branches when a loop condition or conditional path is never false. section 3.8
  • Check indexOf()-based loops for branches that fail to update the search position. section 3.8
static boolean hasPercentD(String str) {
  int pos = 0;
  while (true) {
    pos = str.indexOf('%', pos);
    if (pos == -1 || pos == str.length() - 1) {     #1
      return false;                                
    }                                              
    char c = str.charAt(pos + 1);
    if (c == 'd') {     #2
      return true;     
    }                  
    if (c == '%') {     #3
      pos += 2;       
    }                 
  }
}

Inspect the focused hasPercentD loop and its numbered conditional branches. section 3.8

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains missing branches through an infinite-loop example and testing guidance, but stops short of coverage-tool configuration.
Examples
Uses a hasPercentD loop with inputs such as "%%%%" and "%%d%%%d" to illustrate branch-sensitive tests.
What it assumes
Assumes unit-testing familiarity and basic control-flow understanding while emphasizing loop iteration behavior.
What you can do after
Diagnose/debug with it by locating untested loop branches and adding tests for zero, single, and repeated iterations.
How it connects
Connects branch coverage with line coverage, instruction coverage, unit testing, loops, static analysis, and indexOf().

Also explained in

Compare how 3 books explain branch coverage →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.