Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Tutorial
  • Java Spring
  • Spring Interview Questions
  • Java SpringBoot
  • Spring Boot Interview Questions
  • Spring MVC
  • Spring MVC Interview Questions
  • Java Hibernate
  • Hibernate Interview Questions
  • Advance Java Projects
  • Java Interview Questions
Open In App
Next Article:
JUnit 5 – JaCoCo Code Coverage
Next article icon

JUnit 5 – JaCoCo Code Coverage

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In simple terms, code coverage means measuring the percentage of lines of code that are executed during automated tests. For example, if you have a method containing 100 lines of code and you are writing a test case for it, code coverage tells you briefly how many of those lines were actively exercised by the test.

JaCoCo Code Coverage with the Example of String Palindrome

JaCoCo is an open-source library for measuring Java code coverage under the Eclipse Public License.

Let's initiate by creating a Maven project within Eclipse. The overall structure of the folder will look like this:

Project Structure

Once the standalone application is established, navigate to the main class i.e. App.java and compose a method to determine whether a given string input qualifies as a palindrome.

Java
package coverage.jacoco;  public class App {      public boolean isPalindrome(String input) {          if (input == null) {             throw new IllegalArgumentException("input shouldn't be null");         }          if (input.equals(reverse(input))) {             return true;         } else {             return false;         }     }      private String reverse(String input) {         String rev = "";         for (int i = input.length() - 1; i >= 0; i--) {             rev = rev + input.charAt(i);         }         return rev;     }  } 

After successfully writing the palindrome-checking method, now we will test it. But before we start writing the test, we need to add few things to our project's pom.xml file that are JUnit5 dependency and JaCoCo plugin. After adding, the pom.xml file will look like below:

XML
<project xmlns="http://maven.apache.org/POM/4.0.0"           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">   <modelVersion>4.0.0</modelVersion>    <groupId>JaCoCo-demo</groupId>   <artifactId>jacoco</artifactId>   <version>0.0.1-SNAPSHOT</version>   <packaging>jar</packaging>    <name>jacoco</name>   <url>http://maven.apache.org</url>    <properties>     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>   </properties>    <dependencies>          <!--JUnit5 Dependency-->     <dependency>       <groupId>org.junit.jupiter</groupId>       <artifactId>junit-jupiter-engine</artifactId>       <version>5.9.1</version>       <scope>test</scope>     </dependency>        </dependencies>    <build>          <!--jacoco-maven-plugin-->     <plugins>       <plugin>         <groupId>org.jacoco</groupId>         <artifactId>jacoco-maven-plugin</artifactId>         <version>0.8.11</version>         <executions>           <execution>             <id>prepare-agent</id>             <goals>               <goal>prepare-agent</goal>             </goals>           </execution>           <execution>             <id>report</id>             <phase>test</phase>             <goals>               <goal>report</goal>             </goals>           </execution>         </executions>       </plugin>     </plugins>        </build>    </project> 


Now, put App.java to the test and see how JUnit5 and JaCoCo work. We will do this using two easy steps.

Phase: Testing the Reverse String Method

Step 1: Create a Test File: Let's make a new file called "AppTest.java" specifically for testing the reverse string method. This is where we'll write our first test case!

Folder Structure

AppTest.java:

Java
package coverage.jacoco;  import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import coverage.jacoco.App;   public class AppTest {      String input1 = "noon";       //String input     App app = new App();     boolean expected=true;      @Test     public void isPalindromeTest() {         assertTrue(app.isPalindrome(input1));         //assertTrue test method          } } 


Step 2: Run the Test Maven-Style: Now that our test is ready, it's time to see how much code it covers. To do this, we'll run the project as a Maven Test. Here's how:

  • Right-click on the main project folder in your IDE.
  • Look for an option called "Run As" and select "Maven Test."
Run As->Maven test

Step 3: Find the Coverage Report: Once the test runs, it will create a report showing us which parts of the code were tested and which were not. Here's how to find it:

  • Look for a folder called "target" inside your main project folder. It's like a treasure chest holding the results of our test run!
  • Open up the "target" folder, then the "site" folder, and finally the "jacoco" folder.
  • You will see a file named "index.html"—that's our coverage report! Click on it to take a peek inside.Project Structure

When we click on "index.html," it will open in our default browser, displaying a visual overview of our project's code coverage.

Coverage = 84%

Click on the package name, which is "coverage.jacoco," to reveal the class for which we wrote a test.

Code coverage for App.java

Click on "App.java" under the "Element" column. You'll see lines highlighted in green, indicating the code sections successfully tested by our written test. To achieve 100% code coverage, focus on writing tests for the methods highlighted in red.Test Covered only one Method

Phase 2: Conquering Complete Coverage

To achieve the 100% code coverage, let's craft tests for all remaining methods. Upon completion, our AppTest.java file will look like this:

Java
package coverage.jacoco;  import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import coverage.jacoco.App;  public class AppTest {      String input1 = "noon";     App app = new App();     boolean expected=true;      @Test     public void isPalindromeTest() {         assertTrue(app.isPalindrome(input1));     }      @Test     public void isNotPalindromeTest() {         assertFalse(app.isPalindrome("abc"));     }      @Test     public void isNotPalindromeExceptionTest() {         assertThrows(IllegalArgumentException.class, () -> app.isPalindrome(null));     } } 

Do the steps that we have done in Phase 1, Step 2, to generate a fresh coverage report. Code Coverage = 100%

Click on the package name, "coverage.jacoco" to view the class for which we've written a test.Code Coverage for App.Java

Now click on the App Class present under element column, we will see all the methods present in our code snippet are tested by our written test.Test Covered all Methods

Key Takeaways of the Testing

Testing for Main Features Isn't Enough: In Phase 1, we saw that even when we write tests for primary features, they might not test all the methods written by us. We have seen red marks in our results, indicating untested methods within our code snippets.

Coverage Targets Vary: The ideal code coverage percentage depends on project-specific factors. It is not necessary to achieve 100% code coverage in every case. If our written tests cover all the key feature methods, we can conduct a risk analysis to decide whether to write further tests. This can save time while working towards project deadlines.


Next Article
JUnit 5 – JaCoCo Code Coverage

S

sushant_bagul
Improve
Article Tags :
  • Java
  • Geeks Premier League
  • Advance Java
  • JUnit
  • Geeks Premier League 2023
Practice Tags :
  • Java

Similar Reads

    JUnit 5 – @BeforeEach
    JUnit 5 is a widely used testing framework in the Java ecosystem, designed to address the limitations of its predecessor, JUnit 4. The JUnit framework allows developers to write and run effective tests for their Java applications, ensuring that the code functions correctly and continues to work as e
    6 min read
    JUnit 5 – @AfterEach
    JUnit 5 is the recent version of the JUnit testing framework. JUnit 5 is the most powerful version compared to the other versions because it consists of enhanced features that provide the foundation for developer-side testing. Moreover, writing and running the unit tests with the JUnit 5 testing fra
    4 min read
    JaCoCo with IntelliJ IDEA
    Testing is a most essential part of a software development lifecycle. Without testing, the software is not ready for deployment. To test Java applications we mostly used Junit. JUnit framework is a Java framework that is used for testing. And now, JUnit is used as a standard when there is a need to
    3 min read
    JUnit 5 – Gradle Dependency
    JUnit is one of the most widely used unit testing frameworks for Java-based applications. Over the years, JUnit has evolved with different releases, including JUnit 3 and JUnit 4, which are now considered slightly outdated. The latest release, JUnit 5, was introduced to support modern Java features
    7 min read
    How to Generate Code Coverage Report with JaCoCo in Java Application?
    Testing is a most important part of a software development lifecycle. Without testing, the software is not ready for deployment. To test Java applications we mostly used Junit. JUnit framework is a Java framework that is used for testing. And now, JUnit is used as a standard when there is a need to
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences