Verify JaCoCo code coverage report generation after running JUnit tests
Preconditions (3)
✅ Expected Result: JaCoCo generates a coverage report showing coverage percentages for classes tested by JUnit tests
import static org.junit.jupiter.api.Assertions.*; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.jupiter.api.Test; public class JaCoCoReportTest { @Test public void testJaCoCoReportExistsAndHasContent() throws Exception { // Path to the JaCoCo report Path reportPath = Paths.get("target/site/jacoco/index.html"); // Assert the report file exists assertTrue(Files.exists(reportPath), "JaCoCo report file should exist"); // Read report content String content = Files.readString(reportPath); // Assert the report contains coverage data (check for a known marker like 'Coverage Summary') assertTrue(content.contains("Coverage Summary") || content.contains("class coverage"), "JaCoCo report should contain coverage summary"); } }
This JUnit 5 test checks if the JaCoCo coverage report is generated after running tests.
First, it verifies the report file target/site/jacoco/index.html exists. This confirms the report was created.
Then, it reads the report content as a string and checks for a known phrase like Coverage Summary to ensure the report contains coverage data.
This approach uses standard Java file APIs and JUnit assertions to validate the presence and content of the coverage report, following best practices for automation.
Now add data-driven testing to verify JaCoCo reports for multiple Maven modules with different paths
pom.xml file?pom.xml:
<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>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
What will happen when you run mvn test?mvn test. What is the most likely cause?build.gradle?Pass the test and this pattern moves unknown