In software testing, code coverage is used to measure how much of the code is tested. What exactly does code coverage measure?
Think about what 'coverage' means in everyday life, like covering a surface.
Code coverage measures how many lines or parts of the code are actually run when tests are executed. It shows how much of the code is 'covered' by tests.
Given this JUnit test and code, what coverage percentage will be reported?
public class Calculator { public int add(int a, int b) { return a + b; } public int subtract(int a, int b) { return a - b; } } import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class CalculatorTest { @Test public void testAdd() { Calculator calc = new Calculator(); assertEquals(5, calc.add(2, 3)); } }
Only one method is tested out of two.
The test only calls the add method, so only that method's code is executed. The subtract method is not tested, so coverage is 50%.
You want to assert that your JUnit tests cover all branches of a method. Which assertion best reflects this completeness?
Complete coverage means 100% coverage.
To confirm all branches are covered, coverage must be 100%. The assertion checks this exactly.
You have written JUnit tests that pass, but coverage reports only 80%. What is the most likely reason?
Passing tests do not guarantee all code paths run.
Tests may pass but not cover all code paths, so coverage is less than 100%. This shows incomplete test coverage.
Which configuration or tool setup ensures JUnit tests measure branch coverage accurately?
Coverage tools need to instrument code to measure branches.
JaCoCo is a popular coverage tool that instruments code at runtime. Enabling branch coverage in its settings ensures accurate measurement of all branches during JUnit test execution.