0
0
JUnittesting~5 mins

Coverage reports in JUnit

Choose your learning style9 modes available
Introduction

Coverage reports show which parts of your code were tested. They help find untested code so you can improve your tests.

After writing tests to see how much code they check.
Before releasing software to ensure important parts are tested.
When fixing bugs to confirm the fix is covered by tests.
During code reviews to verify test completeness.
When adding new features to track test coverage.
Syntax
JUnit
Use a coverage tool like JaCoCo with JUnit tests.

Example Maven plugin configuration:

<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.8</version>
  <executions>
    <execution>
      <goals>
        <goal>prepare-agent</goal>
      </goals>
    </execution>
    <execution>
      <id>report</id>
      <phase>verify</phase>
      <goals>
        <goal>report</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Coverage tools run alongside your tests to collect data.

Reports can be in HTML, XML, or other formats for easy reading.

Examples
Run tests and then generate a coverage report using Maven commands.
JUnit
mvn clean test
mvn jacoco:report
Maven plugin setup to collect coverage data during tests and generate reports automatically.
JUnit
<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.8</version>
  <executions>
    <execution>
      <goals>
        <goal>prepare-agent</goal>
      </goals>
    </execution>
    <execution>
      <id>report</id>
      <phase>verify</phase>
      <goals>
        <goal>report</goal>
      </goals>
    </execution>
  </executions>
</plugin>
Sample Program

This test covers only the add method of Calculator. The subtract method is not tested, so coverage report will show partial coverage.

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

class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }
}

public class CalculatorTest {
    @Test
    public void testAdd() {
        Calculator calc = new Calculator();
        assertEquals(5, calc.add(2, 3));
    }
}
OutputSuccess
Important Notes

Coverage does not guarantee bug-free code but helps find untested parts.

High coverage is good, but tests must also check correct behavior.

Use coverage reports regularly to improve test quality over time.

Summary

Coverage reports show which code is tested and which is not.

Use tools like JaCoCo with JUnit to generate coverage reports.

Review reports to improve your tests and software quality.