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 occur in the program code when we use conditional or branching statements.
Examples
- if statement
- nested if-else ladder
- switch case statements
- looping statements like for, while, etc.
Branch Coverage
The mathematical formula to compute the coverage metric is as follows:
- The number of branches exercised is the number of branches in the program executed during the testing.
- The Total number of branches is the total number of decision points in the program under test.
Example
Consider a software program and assume that it contains 4 branches. The software test cases cover 3 branches.
Let’s compute the branch coverage metric based on the given formula.
Based on the given data:
Number of covered branches = 3
Total number of branches in the program = 4
As per the formula:
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 is considered true. The False branch is covered when the if condition is considered false.
Code 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); } }
The test covers a branch 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 tests do not cover the branch.
Line vs Branch Coverage
Statement coverage does not imply branch coverage. If we remove bc.demo(false) statement we can still achieve 100% Statement coverage but not branch coverage.
A high percentage of this metric indicates that a significant portion of the software code has been tested, increasing confidence. However, it’s important to note that high branch coverage does not guarantee the absence of all defects, as it only measures the execution of different decision paths.
The goal of branch coverage is to ensure that all possible decision outcomes within the code have been exercised during testing. It helps identify areas of the code that have not been executed, which may indicate potential bugs or untested code paths.
More information:
https://en.wikipedia.org/wiki/Code_coverage
Related
Statement Coverage
https://www.testingdocs.com/statement-coverage/
—
Software Testing Tutorials:
https://www.testingdocs.com/software-testing-tutorials/