How to check code coverage with JaCoCo agent?

6.4k views Asked by At

I am going to deploy application with JaCoCo agent to production environment to let it work for some time. The result should help me identify the parts of code I can get rid of.

I started some research around the topic and prepared HelloWorld application:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello world");
    }
}

Then I compiled the class: "javac HelloWorld.java" and got HelloWorld.class file.

Now I run the app with the following command: "java -javaagent:jacocoagent.jar HelloWorld" the program executes and jacoco binary is generated. The file contains some binary data.

Everything looks fine but the coverage report shows 0% coverage although it should be 100%.

Has anyone faced this issue or correct me what I am doing the bad way?

1

There are 1 answers

2
bhdrkn On BEST ANSWER

I generated full report using this steps. Since I use maven for this kind of operations I added maven after your steps. I created HelloWorld.java just copying from your question. Then I follow these steps:

javac HelloWorld.java which outputs HelloWorld.class Then I created jacoco.exec by executing java -javaagent:jacocoagent.jar HelloWorld

Then I created a pom.xml file which contents are like this.

<?xml version="1.0" encoding="UTF-8"?>
<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>test</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

    <name>test</name>


    <build>
        <plugins>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.5.201505241946</version>
            </plugin>
        </plugins>
    </build>

After that I created a target/classes directory. I copied jacoco.exec to target/ and HelloWorld.class to target/classes.

Then I executed mvn jacoco:report which generates a report to target/site/jacoco. Which contains correct coverage information.

I know using maven may not sound good for a simple application. But I don't know any other way to generate reports from jacoco.exec. By the way your maven plugin version and jacocoagent version must match.

And here the result I get.result