Generate and verify code coverage report for Calculator class
Preconditions (3)
โ
Expected Result: The coverage report shows 100% line and branch coverage for the Calculator class methods tested
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import java.io.File; public class CalculatorTest { @Test public void testAdd() { Calculator calc = new Calculator(); assertEquals(5, calc.add(2, 3)); assertEquals(-1, calc.add(2, -3)); } @Test public void testSubtract() { Calculator calc = new Calculator(); assertEquals(1, calc.subtract(3, 2)); assertEquals(5, calc.subtract(2, -3)); } @Test public void testCoverageReportExists() { // Assuming Maven default target directory and JaCoCo report path File report = new File("target/site/jacoco/index.html"); assertTrue(report.exists(), "Coverage report should exist after tests run"); } } // Sample Calculator class class Calculator { public int add(int a, int b) { return a + b; } public int subtract(int a, int b) { return a - b; } } /* Note: To generate coverage report, run: mvn clean test jacoco:report Then open target/site/jacoco/index.html to verify coverage manually. */
The test class CalculatorTest contains three tests:
add method with two cases.subtract method with two cases.The Calculator class is simple with two methods to test.
Running mvn clean test jacoco:report will execute tests and generate the coverage report.
The coverage report file existence is asserted programmatically to confirm report generation.
Manual verification of coverage percentage is recommended by opening the HTML report in a browser.
Now add data-driven testing for Calculator add method with 3 different input pairs
coverage report in JUnit testing?Lines covered: 80
Lines missed: 20branchCoverage activates it.@BranchCoverage exists; changing framework or test count doesn't enable branch coverage reporting.branchCoverage option in JaCoCo plugin settings -> Option DPass the test and this pattern moves unknown