Branch Coverage
Overview
Branch coverage is a code coverage metric to check that all the branches in the application source code are tested at least once. Branches in the code when we use conditional statements or branching statements. Examples
- if statement
- nested if-else ladder
- switch case statements
- looping statements like for, while etc.
Branch Coverage
Mathematical formula to compute the coverage metric is as follows:
Example
Assume 4 branches in the program. 3 branches are covered by the tests.
Branch Counters:
Number of Covered branches = 3
Total number of branches = 4
BC = (3/4)*100
= 75%
Code Example
Let’s see branch code coverage in action with a simple code that uses an if statement. The if statement has two branches. One True branch and one False branch. The True branch is covered or executed when the if condition evaluates to true. The False branch is covered when the if condition evaluates to false.
Listing
public class BranchCoverageDemo { public void demo(boolean flag) { if(flag) { System.out.println("Branch Code Demo"); } } public static void main(String[] args) { BranchCoverageDemo bc = new BranchCoverageDemo(); bc.demo(true); bc.demo(false); } }
A branch is covered by the test if it is executed during the test run. The coverage report highlights the covered branches with green color. The red color highlight indicates that the branch is not covered by the tests.
Line vs Branch Coverage
Statement coverage do not imply branch coverage. If we remove bc.demo(false) statement we can still achieve 100% Statement coverage but not branch coverage.
Related
Statement Coverage
https://www.testingdocs.com/statement-coverage/
—
Software Testing Tutorials: