Knowledge Base > Cover CLI > Measuring the coverage of a main method

Measuring the coverage of a main method

This article provides guidance how to measure and visualize the coverage associated to executing a Java main class.

Using Intellij IDEA

  1. Load the project in Intellij IDEA.
  2. Right-click on the small green ‘play’ button next to the method and then ‘Run <main method> with Coverage’:

Maven projects

  1. Compile the project:

    mvn compile
    
  2. Copy the project dependencies using the Maven goal dependency:copy-dependencies:

    mvn dependency:copy-dependencies
    
  3. Get the JaCoCo agent:

    mvn dependency:copy -Dartifact=org.jacoco:org.jacoco.agent:0.8.8:jar:runtime
    
  4. Run the main method with the JaCoCo agent:

    java -javaagent:target/dependency/org.jacoco.agent-0.8.8-runtime.jar \
       -cp 'target/classes/:target/dependency/*' \
       com.example.YourMainClass
    
  5. The coverage report is at ./jacoco.exec, you can now visualize it in Intellij.

Complete example on Spring Pet Clinic:

git clone https://github.com/spring-projects/spring-petclinic
cd spring-petclinic

mvn compile
mvn dependency:copy-dependencies
mvn dependency:copy -Dartifact=org.jacoco:org.jacoco.agent:0.8.8:jar:runtime

java -javaagent:target/dependency/org.jacoco.agent-0.8.8-runtime.jar \
   -cp 'target/classes/:target/dependency/*' \
   org.springframework.samples.petclinic.PetClinicApplication

Gradle projects

  1. Modify the build.gradle file to configure the application and jacoco plugins this way:

    plugins {
      id 'application'
      id 'jacoco'
    }
    
    application {
      mainClass = 'com.example.YourMainClass'
    }
    
    jacoco {
      applyTo run
    }
    
  2. Run the application

    ./gradlew run
    
  3. The coverage report is at ./build/jacoco/run.exec, you can now visualize it in Intellij.

Complete example on Spring Pet Clinic:

git clone https://github.com/spring-projects/spring-petclinic
cd spring-petclinic

# modify the build.gradle file, to introduce the following changes:
git diff build.gradle
 --- a/build.gradle
 +++ b/build.gradle
 @@ -2,6 +2,8 @@ plugins {
    id 'org.springframework.boot' version '2.6.6'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
 +  id 'application'
 +  id 'jacoco'
  }

  apply plugin: 'java'
 @@ -39,3 +41,11 @@ dependencies {
  test {
    useJUnitPlatform()
  }
 +
 +application {
 +  mainClass = 'org.springframework.samples.petclinic.PetClinicApplication'
 +}
 +
 +jacoco {
 +  applyTo run
 +}

# run the application
./gradlew run