Thursday, June 9, 2022

Merged Code Coverage with Java and Jacoco

 

Introduction

Code coverage is the percentage of code coverage under any tests, ideally automated tests. Code coverage measurement simply determines which statements in a piece of code have been exercised through a set of test executions, and which statements have not. Here we are going to use Java Code Coverage or JaCoCo which is a free code coverage library for java.

One of things we are trying to do here on this example extra, is to combine coverage from multiple test executions, which is a very common case when coverge is gathered from multiple test-suites run on the same piece of code(SUT).

Steps to use Jacoco using java agent:

    1.    Set up the jacoco agent giving a specific port number for required service for which jacoco needs to be attached.
   "-javaagent:<path-to-application>/src/main/resources/lib/jacocoagent.jar=address=*,port=<port-number>,destfile=jacoco-it.exec,output=tcpserver"

    2.    Start the services/execute code with the jacoco agent.


    3.    Run any tests which exercises the code.


    4.    Dump the results

 

Ex:- java -jar /Users/work/jacoco/lib/jacococli.jar dump --address localhost --port 36320 --destfile /Users/work/jacoco/reports/jacoco-it1.exec    

java -jar /Users/work/jacoco/lib/jacococli.jar dump --address localhost --port 36330 --destfile /Users/work/jacoco/reports/jacoco-it2.exec




    5.    Collect instrumentation: 



            1. For a Single report:



            java -jar /Users/work/jacoco/lib/jacococli.jar report /Users/work/mys/mysqlaas-integration-tests/tester/target/jacoco-it1.exec --classfiles /Users/work/mys/cp/api/target/classes/com --sourcefiles /Users/work/mys/cp/api/src/main/java/ --html /Users/work/mys/tests/target/jacoco-report

            2. For Merging instrumentation of 2 or more reports:



            Ex:- java -jar /Users/work/jacoco/lib/jacococli.jar merge /Users/work/jacoco/reports/jacoco-it1.exec /Users/work/jacoco/reports/jacoco-it2.exec --destfile /Users/work/jacoco/reports/jacoco-it.exec
         

         3. Reports Generation types:

          Using Classes:

  java -jar /Users/work/jacoco/lib/jacococli.jar report /Users/work/jacoco/reports/jacoco-it.exec --classfiles /Users/work/cp/api/target/classes/com  --classfiles /Users/work/cp/worker/target/classes/com --sourcefiles /Users/work/cp/api/src/main/java/ --sourcefiles /Users/work/cp/worker/src/main/java/ --html /Users/work/jacoco/reports/jacoco-report




         Using JAR’S:

  java -jar /Users/work/jacoco/lib/jacococli.jar report /Users/work/jacoco/reports/jacoco-it.exec --classfiles /Users/work/cp/api/target/mysqlaas-api-0.0.1-SNAPSHOT.jar  --classfiles /Users/work/cp/worker/target/mysqlaas-worker-0.0.1-SNAPSHOT.jar --sourcefiles /Users/work/cp/api/src/main/java/ --sourcefiles /Users/work/cp/worker/src/main/java/ --html /Users/work/jacoco/reports/jacoco-report