Junit: Code coverage by using JaCoCo


Why Code Coverage Require while writing JUnit?

Code coverage is a matric indicator that shows the line of code are executed while running the automated JUnit test cases. This helps developer to identify that any unit test is not missing for developed code or newly added functionality of code so that improve the code quality and reduce number of bugs on time of integration testing.

While audit of your application source code auditor also asked for Code Coverage report so that observe your written Junit test cases covering complete application or not.

For Java development there are couple of tools for Code Coverage like Cobertura and Jacoco etc. Here you will learn about the integration of JACOCO with maven project.

JCOCO Code Coverage Plugin Integration with Eclipse/STS

Note : Cobertura support till Java version 8 only while JACOCO support all the Java 5 and above.

Code Coverage Tools generate report in percentage ratio as below in screen shot. Each header section described in detail in this table.

Junit Code Coverage

You can further extend this package section to get more code coverage detail on class and method level. You will get to know more detail in further sections.

Here these color represent as :

  • Green: Code is tested or covered
  • Red: Code is not tested or covered
  • Yellow: Code is partially tested or covered
HeaderDescription
INSTRUCTION
BRANCHAll the if-else or switch statements are consider as branch and represent as diamond in a method that can be executed or missed.
No coverage (Red diamond): No branches in the line has been executed.
Partial coverage (Yellow diamond): Only a part of the branches in the line have been executed.
CYCLOMATIC COMPLEXITYhttps://en.wikipedia.org/wiki/Cyclomatic_complexity
LINEConsider as executed when at least one instruction that is assigned to this line has been executed.
No coverage (Red): No instruction in the line has been executed.
Partial coverage (Yellow): Only a part of the instruction in the line have been executed.
Full coverage (Green): All instructions in the line have been executed
METHODConsider as executed when one of the instruction has been executed.
CLASSConsider as executed when one of the method has been executed.
JUnit Code Coverage Criteria

Implementation of Code Coverage

In this further section you will learn about the implementation of Code Coverage for Junit. Here we are using dependency as below:

  • JUnit 5
  • Maven 4
  • Maven Surefire plugin 3.0.0-M5
  • Jacoco 0.8.2 (Code Coverage library)

POM.XML

You can make following changes in your maven java application pom.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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.FacingIssuesOnIT</groupId>
  <artifactId>maven-junit-code-coverage-Jacoco</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Maven-junit-CodeCoverage-Jacoco</name>
  <description>Maven JUnit Code Coverage</description>
  <properties> 
     <maven.compiler.source>1.8</maven.compiler.source>
     <maven.compiler.target>1.8</maven.compiler.target>    
	<java.version>1.8</java.version>
	<!-- add property to enable or disable code coverage by default id false for Jacoco -->
	<jacoco.skip>false</jacoco.skip>
</properties>
<dependencies>
<!-- Junit 5 -->
	<dependency>
		<groupId>org.junit.jupiter</groupId>
		<artifactId>junit-jupiter-engine</artifactId>
		<version>5.5.2</version>
	</dependency>
</dependencies>
	<build>
		<plugins>
		<!-- Maven plugin for surefire with Dependency junit 5 -->
			<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M5</version>
            <dependencies>
                <dependency>
                    <groupId>org.junit.jupiter</groupId>
                    <artifactId>junit-jupiter-engine</artifactId>
                    <version>5.5.2</version>
                </dependency>
            </dependencies>
        </plugin>
        <!-- Jacoco plug in for code coverage -->
			<plugin>
				<groupId>org.jacoco</groupId>
				<artifactId>jacoco-maven-plugin</artifactId>
				<version>0.8.2</version>
				<configuration>
					<!-- exclude classes for code coverage -->
					<excludes>
						<exclude>**/*fiot/*Application.class</exclude>
						<exclude>fiot/controller/*</exclude>
					</excludes>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>prepare-agent</goal>
						</goals>
					</execution>
					<!-- attached to Maven test phase -->
					<execution>
						<id>jacoco-report</id>
						<phase>test</phase>
						<goals>
							<goal>report</goal>
						</goals>
						<!-- default target/site/jacoco/* you can define your directory for code coverage report -->
						<configuration>
							<outputDirectory>target/jacoco-report</outputDirectory>
							<skip>${jacoco.skip}</skip>
						</configuration>
					</execution>
					<!-- Define rule for successful build based on code code coverage criteria -->
					<execution>
						<id>jacoco-check</id>
						<goals>
							<goal>check</goal>
						</goals>
						<configuration>
							<rules>
								<rule>
								<!-- When code coverage is 90% and no class missed then consider for successful build -->
									<element>PACKAGE</element>
									<limits>
										<limit>
											<counter>LINE</counter>
											<value>COVEREDRATIO</value>
											<minimum>0.9</minimum>
										</limit>
										<limit>
											<counter>CLASS</counter>
											<value>MISSEDCOUNT</value>
											<maximum>0</maximum>
										</limit>
									</limits>
								</rule>
							</rules>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

Here is more detail about the Jacoco code coverage implementation.

Maven Junit Code Coverage Implementation Detail

Now lets create some classes by some code implantation and check this code coverage implementation by implementing Junit.

Here i have created one Maven Java project with below directory/file structure.

Maven Junit Code Coverage Example

Implement some code as below:

Calculator.java

package com.FacingIssuesOnIT;

public class Calculator {

	   public double divide(int a, int b)
	   {
		   if(b==0)
		   {
			   throw new ArithmeticException();
		   }
		   else
		   {
		   return a/b;
		   }
	   }

	    public int multiply(int a, int b) {
	        return a * b;
	    }
	    
	    public int add(int a, int b) {
	        return a + b;
	    }
}

Address.java

package com.FacingIssuesOnIT;

public class Address {
  public String printAddress()
  {
	  return "Facing Issues On IT \n Learn from Others Experience";
  }
}

CalculatorTest.java

You can write your own Junit test cases or use in git hub by following below link. Maven JUnit Code Coverage Example

Junit Test Cases

Code Coverage report

After writing test cases you can execute same by mvn test and verify the report in folder {application path}/target/jacoco-report/index.html

It will generate report as mentioned in below screen. Here Green percentage showing code coverage for JUnit while red showing for missing Junit for code.

Maven Junit Code Coverage Report

To get in-depth detail on code coverage on class and method level you can extend by clicking package.

Maven Junit code coverage report on class level

On further extend by click on class you will het detail on method level.

Maven Junit Code Coverage report on method level

On further extend by click on particular method you will get detail about the line and branch level code coverage.

Maven JUnit Code Coverage on Line and branch level

After collecting all such information you can write junit test cases for all these missing lines/method/branch (red) of statements.

Code Coverage Rules for application build

In the above example, I have define rule for code coverage as 90% instruction execution and missing class as 0. Even If our implemented Junit executed successfully but code coverage criteria is not match with define rules then our maven install will fail and throw exception as below .

[ERROR] Failed to execute goal org.jacoco:jacoco-maven-plugin:0.8.2:check (jacoco-check) on project maven-junit-code-coverage-Jacoco: Coverage checks have not been met. See log for details. -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.

Once all the missing Junit will implement and criteria will match successful then build sucessfully.

Conclusion

In this blog you learn about the implementation of code coverage for Unit and defining rule to make build. Some times while audit of you application code quality auditor also asked about the JUnit code coverage report so that auditor can verify the written Junit covering the complete source code of your application.

References

https://www.eclemma.org/jacoco/trunk/doc/maven.html

Source Code

Download Maven Junit Code Coverage Source Code

If this example this Junit Code Coverage detail help you like post make comments. In case you are facing any issue while implementing share detail will try to help you.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s