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
- Load the project in Intellij IDEA.
- Right-click on the small green ‘play’ button next to the method and then ‘Run <main method> with Coverage’:
Maven projects
-
Compile the project:
mvn compile
-
Copy the project dependencies using the Maven goal dependency:copy-dependencies:
mvn dependency:copy-dependencies
-
Get the JaCoCo agent:
mvn dependency:copy -Dartifact=org.jacoco:org.jacoco.agent:0.8.8:jar:runtime
-
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
-
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
-
Modify the
build.gradle
file to configure theapplication
andjacoco
plugins this way:plugins { id 'application' id 'jacoco' } application { mainClass = 'com.example.YourMainClass' } jacoco { applyTo run }
-
Run the application
./gradlew run
-
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