Basics of Code Coverage for your Unit Tests
A high coverage percentage does not guarantee freedom from bugs. It only shows which parts of your code execute during testing.
Below are three different types of coverage what you can use for your projects:
- Statement Coverage
- Tracks each statement that runs.
- Formula:
- Branch Coverage
- Checks each decision point (if/else) in the code.
- Formula:
- Path Coverage
- Focuses on each unique path through the code.
- Useful in complex applications.
Statement Coverage = (Number of executed statements / Total statements) * 100
Branch Coverage = (Number of executed branches / Total branches) * 100
You can use these metrics with popular tools like JaCoCo (Java), Coverage.py (Python), and Istanbul (JavaScript).
Example in Python
def add_numbers(a, b):
if a > 0 and b > 0:
return a + b
return 0
# Test cases
def test_add_positive():
result = add_numbers(2, 3)
assert result == 5
def test_add_non_positive():
result = add_numbers(-1, 3)
assert result == 0
- Two tests run different branches in this function.
- This covers statements and branches but does not check every path in larger code blocks.
Example in Java
public class Calculator {
public int multiply(int x, int y) {
if (x == 0 || y == 0) {
return 0;
}
return x * y;
}
}
// JUnit test
import static org.junit.Assert.*;
import org.junit.Test;
public class CalculatorTest {
@Test
public void testMultiplyNonZero() {
Calculator calc = new Calculator();
assertEquals(6, calc.multiply(2, 3));
}
@Test
public void testMultiplyZero() {
Calculator calc = new Calculator();
assertEquals(0, calc.multiply(0, 5));
}
}
- Each test covers a different branch.
- You can expand tests to include more input variations.
Below is a summary table of coverage types:
Coverage Type | What it Measures | Example Tools |
Statement | Executed lines of code | JaCoCo, Coverage.py, Istanbul |
Branch | Executed branches in decisions | JaCoCo, Coverage.py, Istanbul |
Path | Each path through the code | Fewer mainstream tools |
Focus on a reasonable coverage target. Some teams aim for 70ā80%. Pick a standard that fits your applicationās risk level and complexity. Remember that code coverage does not confirm absence of defects. It only shows test execution depth.
Use these metrics to improve your test practices and find gaps. Combine coverage data with reviews and other testing methods for a broader perspective.
Happy Testing,
Csaba
P.s.: oh btw. if you want to learn more about this, join our community of testers here