Introduction
Coverage shows how much of your code is tested. It helps find parts not checked by tests.
Coverage shows how much of your code is tested. It helps find parts not checked by tests.
No direct code syntax; coverage is measured by tools that analyze test runs.// Example: JUnit test class import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class CalculatorTest { @Test void testAdd() { Calculator calc = new Calculator(); assertEquals(5, calc.add(2, 3)); } }
// Example: Missing test for subtract method class Calculator { int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } }
This test class only tests the add method. Coverage tools will report that subtract is not covered, showing test incompleteness.
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class Calculator { int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } } class CalculatorTest { @Test void testAdd() { Calculator calc = new Calculator(); assertEquals(5, calc.add(2, 3)); } }
Coverage helps find untested code but does not check test quality.
Use coverage with other testing practices for best results.
Coverage measures how much code tests run through.
It shows which parts of code are not tested yet.
Higher coverage helps improve test completeness but is not the only goal.
calculate?
public class Calculator {
public int calculate(int x) {
if (x > 0) return x * 2;
else return 0;
}
}
@Test
public void testCalculatePositive() {
Calculator c = new Calculator();
assertEquals(4, c.calculate(2));
}isValid:
public boolean isValid(int n) {
if (n > 0) return true;
else return false;
}
@Test
public void testIsValid() {
assertTrue(isValid(1));
}public String classify(int age) {
if (age < 13) return "child";
else if (age < 20) return "teen";
else return "adult";
}
To achieve 100% coverage, which set of test inputs should you include in your JUnit tests?Pass the test and this pattern moves unknown