0
0
JUnittesting~5 mins

Line and branch coverage in JUnit

Choose your learning style9 modes available
Introduction

Line and branch coverage help us check how much of our code is tested. This shows if tests run all parts of the program.

When you want to see if your tests run every line of your code.
When you want to check if all decision points (like if-else) are tested.
Before releasing software to ensure important parts are not missed.
When improving tests to cover more cases and avoid bugs.
When comparing test quality between different test sets.
Syntax
JUnit
No direct code syntax. Use tools like JaCoCo with JUnit to measure coverage.
Line coverage counts how many lines of code are executed by tests.
Branch coverage checks if all possible paths (true/false) in decisions run.
Examples
This method has two branches: one for a > b true, one for false.
JUnit
// Example Java method
public int max(int a, int b) {
    if (a > b) {
        return a;
    } else {
        return b;
    }
}
This test covers the true branch but not the false branch.
JUnit
// Test case covering only one branch
@Test
public void testMax() {
    assertEquals(5, max(5, 3));
}
This test covers both true and false branches.
JUnit
// Test case covering both branches
@Test
public void testMaxBoth() {
    assertEquals(5, max(5, 3));
    assertEquals(7, max(4, 7));
}
Sample Program

This JUnit test class has two tests. The first test covers only the true branch of the max method. The second test covers both true and false branches.

Using a coverage tool like JaCoCo will show line coverage and branch coverage results for these tests.

JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class CoverageExample {

    public int max(int a, int b) {
        if (a > b) {
            return a;
        } else {
            return b;
        }
    }

    @Test
    public void testMaxTrueBranch() {
        assertEquals(5, max(5, 3));
    }

    @Test
    public void testMaxBothBranches() {
        assertEquals(5, max(5, 3));
        assertEquals(7, max(4, 7));
    }
}
OutputSuccess
Important Notes

Line coverage alone may miss untested decision paths; branch coverage is more thorough.

Coverage tools integrate with build tools like Maven or Gradle for easy reports.

High coverage does not guarantee no bugs but helps find untested code.

Summary

Line coverage checks if each line runs during tests.

Branch coverage checks if all decision paths run.

Use coverage tools with JUnit to measure and improve test quality.