What is branch testing?
Branch testing is a type of white-box testing that is used to test every possible branch in the control flow graph of a program. In branch testing, every branch in the code is executed at least once.
Why do we need branch testing?
We need branch testing because:
- It ensures that no branch in the code leads to abnormal behavior.
- It guarantees that all branches in the code are reached.
- It is a quantitative measure of the code coverage of the program.
How to calculate branch testing
Branch testing of a program is carried out by calculating a metric called branch coverage. Branch coverage is the ratio of the number of branches covered to the total number of branches. Branch coverage can be calculated as:
Example
Consider the code snippet below, which is a simple program to find the maximum of two numbers:
int a = 2;int b = 5;if(a>b){cout<<"a is max";}else{cout<<"b is max";}
Control flow graph
The control flow graph of the code above will be as follows:
Branch testing
Branches
The branches in the control flow graph above are A, B, C, D, E, F, and G.
Branch Coverage
For maximum branch coverage, we take the path:
Path1 = 1A-2B-3C-4D-5F-7
- Covered branches = A, B, C, D, F
- Uncovered branches = E, G
The branch coverage of path1 will be:
Branch coverage = (number of branches covered / total number of branches) x 100
Branch coverage = (5 / 7) x 100
Branch coverage = 71%
Branches E and G are not covered in path1. To cover branches E and G, we take the path:
Path2 = 1A-2B-3C-4E-6G-7
- Covered branches = A, B, C, E, G
- Uncovered branches = D, F
The branch coverage of path2 will be:
Branch coverage = (number of branches covered / total number of branches) x 100
Branch coverage = (5 / 7) x 100
Branch coverage = 71%
For 100% branch coverage, we combine both paths, path1 and path2. The final branch testing of the control flow graph above becomes:
- Path1 = 1A-2B-3C-4D-5F-7
- Path2 = 1A-2B-3C-4E-6G-7
Free Resources