liveBook · Manning

Branch coverage

As explained in Unit Testing Principles, Practices, and Patterns

Branch coverage is a test coverage measure indicating which conditional branches in code are executed by tests.

Branch coverage measures the ratio of conditional branches executed by a test suite to the total branches in production code. It reveals more about test completeness than line coverage, but it remains a negative indicator: low coverage signals trouble, while high coverage does not prove test quality. section 1.3 section 1.6

Figure 1.4. The branch metric is calculated as the ratio of the number of code branches exercised by the test suite and the total number of branches in the production code base.

Use the branch-ratio diagram to distinguish executed conditional paths from total paths. section 1.3

One of two paths covered

For IsStringLong, a test using "abc" exercises the false path but not the true path for strings longer than five characters. The result is 50% branch coverage, even though the test contains an assertion. section 1.3

Apply branch coverage as feedback rather than a target:

  • Investigate low coverage, especially in core system areas. section 1.6
  • Do not impose a required coverage percentage; it creates perverse incentives. section 1.6
  • Check assertions and important behavior separately, because branch coverage does not show whether tests verify outcomes. section 1.6
  • Weigh coverage benefits against test maintenance costs and retain tests with positive net value. section 1.6

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Defines the ratio, demonstrates two paths, and explains limits involving assertions, external libraries, and imposed thresholds.
Examples
Uses an IsStringLong method, a short-string test, a two-path graph, and a 50% branch-coverage result.
What you can do after
Evaluate test-suite completeness, investigate low coverage, and balance coverage benefits against maintenance costs.
How it connects
Connects branch coverage with code coverage, unit testing, assertions, test-suite quality, and third-party libraries.

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 Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.