← Concepts

阅读中文版本

Branch Coverage

Branch coverage measures whether every decision outcome is exercised, catching untested else and short-circuit paths that statement coverage overlooks.

testing

Definition

Branch coverage is a code coverage criterion that counts whether each control-flow branch, such as both sides of an if condition, has been executed by the test suite.

Context and scope

It is used to judge how much decision logic tests exercise, especially around validation and error handling.

Common misconceptions

  • branch coverage is identical to line coverage
  • high branch coverage proves the assertions are meaningful

Anti-patterns

  • chasing branch coverage with tests that assert nothing
  • treating low coverage as automatically acceptable for legacy modules

Related concepts

Authoritative source

https://en.wikipedia.org/wiki/Code_coverage

Definition

Branch coverage is a code coverage criterion that counts whether each control-flow branch, such as both sides of an if condition, has been executed by the test suite.

It is used to judge how much decision logic tests exercise, especially around validation and error handling. Compared to simpler alternatives, this concept fits best when the trade-off it represents is the one the system actually cares about.

When to use it

A common use case is applying it at the boundary where the cost of getting it wrong is highest, and the scenario usually involves a concrete guarantee the system must uphold. Unlike an ad hoc approach, it makes that guarantee explicit, reviewable, and testable.

How it works

A single statement can contain multiple branches, so a line can be executed while one of its decision outcomes remains untested, which is exactly what branch coverage reveals.

Short-circuit operators and ternary expressions create implicit branches that are easy to miss when writing tests.

Trade-offs and alternatives

Coverage counts execution only; it says nothing about whether the assertions would detect a regression, so pair it with mutation testing for real confidence. The main drawback is the extra complexity it introduces, so the benefit should clearly outweigh that cost before a team adopts it.

Common misconceptions

A persistent misconception is that branch coverage is identical to line coverage. Another is that high branch coverage proves the assertions are meaningful. For example, an engineer who assumes otherwise may design around a guarantee that does not actually exist, which only becomes obvious under load or failure.

Anti-patterns to avoid

Two recurring anti-patterns are to chasing branch coverage with tests that assert nothing and to treating low coverage as automatically acceptable for legacy modules. Both tend to surface as hard-to-debug production issues rather than obvious test failures. Related concepts include Stress Testing Beyond Design Limits, Load Testing to Target Concurrency, Approval Testing.