Configuring Jacoco in a Gradle Project

To enable jacoco code coverage in a gradle project, just add the below configuration to your build.gradle file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
apply plugin: 'jacoco'

jacoco {
toolVersion = '0.8.1'
}

jacocoTestReport {
reports {
csv.enabled = false
xml.enabled = false
html.enabled = true
}
afterEvaluate { // (optional) : to exclude classes / packages from coverage
classDirectories.from = files(classDirectories.files.collect {
fileTree(
dir: it,
exclude: [ 'snmaddula/sboot/crud/App.class', 'snmaddula/sboot/util/**' ])
})
}
}

build.dependsOn jacocoTestReport

Now execute gradle clean build in the project directory. You’ll see the output similar to the below one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
12:10:08 PM: Executing tasks 'clean build'...

> Task :clean UP-TO-DATE
> Task :compileJava
> Task :processResources
> Task :classes
> Task :bootJar
> Task :jar SKIPPED
> Task :assemble
> Task :compileTestJava
> Task :processTestResources NO-SOURCE
> Task :testClasses
> Task :test
> Task :check
> Task :jacocoTestReport
> Task :build

BUILD SUCCESSFUL in 9s
7 actionable tasks: 6 executed, 1 up-to-date
12:10:18 PM: Tasks execution finished 'clean build'.

Navigate to build > reports > jacoco > test > html and open index.html using a web browser.

You’ll see a report similar to the one shown below.

That’s all you need to configure jacoco in a gradle project.