JUnit test cases are used to check our application code, whether they are working according to the requirement or not. The Jacoco Maven plugins can be easily integrated with the spring boot applications
We can run our JUnit test cases in Eclipse/STS IDE by right-clicking on the project/file/test method > Run as> JUnit Test. But this method does not generate any report and hence that may not be helpful if we are automating the build with CI/CD pipeline.
Surefire is a test framework project. Apache Maven provides plugin support for Surefire. We can add these plugin details into our application’s pom.xml file to enable the maven command. The maven build process uses this plugin to run the JUnit test cases and generate the test report.
Maven also provides JaCoCo(Java code coverage) plugin. This plugin enables the Maven command to generate code coverage reports.
In this article, we will learn how to add the Surefire and the JaCoCo Maven plugin details into the pom.xml of our spring boot application.
Maven Surefire plugin
We can add the below plugin details to the pom.xml file to generate the surefire report during Maven build. This will run the available test cases and generate the Surefire reports under the directory: target/surefire-reports/ during the build Maven process.
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> </plugin> </plugins> <build>
Maven JaCoCo plugin
Similar to the Maven Surefire plugin, we can also add the JaCoCo Maven plugin to our application’s pom.xml file.
<build> <plugins> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.5</version> <executions> <execution> <id>jacoco-initialize</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>jacoco-site</id> <phase>test</phase> <goals> <goal>report</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
The above build node contains the JaCoCo Maven plugin. The plugin runs during the test phase of the Maven build process. The configuration enables the JaCoCo plugin when we run the Maven command: mvn test.
Running the Maven build
We have added both Surefire and JaCoCo Maven plugins to our application’s build process. It is time to run the build and verify the results. 🙂
Run the test cases by Right click on project > Run As > Maven test.
Below console output shows the successful execution of all the test cases present under the /src/test/java project directory.
The Surefire and JaCoCo reports are generated under the target/ directory as shown below.
We can observe the test results from the generated Surefire report below.
We can check the code coverage report by opening the /target/site/jacoco/index.html file on the web browser.
Below is the code coverage of a Java file from the JaCoCo report.
In this post, we learned how to use Surefire and JaCoCo Maven plugins to generate the JUnit test report and JaCoCo code coverage report.