# The JaCoCo Plugin

The JaCoCo plugin provides code coverage metrics for Java code via integration with JaCoCo.

## Getting Started

To get started, apply the JaCoCo plugin to the project you want to calculate code coverage for.

Example 1. Applying the JaCoCo plugin
build.gradle

    plugins {
        id 'jacoco'
    }

build.gradle.kts

    plugins {
        jacoco
    }

If the Java plugin is also applied to your project, a new task named `jacocoTestReport` is created that depends on the `test` task. The report is available at `$buildDir/reports/jacoco/test`. By default, a HTML report is generated.

## Configuring the JaCoCo Plugin

The JaCoCo plugin adds a project extension named `jacoco` of type JacocoPluginExtension, which allows configuring defaults for JaCoCo usage in your build.

Example 2. Configuring JaCoCo plugin settings
build.gradle

    jacoco {
        toolVersion = "0.8.3"
        reportsDir = file("$buildDir/customJacocoReportDir")
    }

build.gradle.kts

    jacoco {
        toolVersion = "0.8.3"
        reportsDir = file("$buildDir/customJacocoReportDir")
    }

Table 1. Gradle defaults for JaCoCo properties
Property | Gradle default
--- | ---
reportsDir | `$buildDir/reports/jacoco`

## JaCoCo Report configuration

The JacocoReport task can be used to generate code coverage reports in different formats. It implements the standard Gradle type Reporting and exposes a report container of type JacocoReportsContainer.

Example 3. Configuring test task
build.gradle

    jacocoTestReport {
        reports {
            xml.enabled false
            csv.enabled false
            html.destination file("${buildDir}/jacocoHtml")
        }
    }

build.gradle.kts

    tasks.jacocoTestReport {
        reports {
            xml.isEnabled = false
            csv.isEnabled = false
            html.destination = file("${buildDir}/jacocoHtml")
        }
    }

## Enforcing code coverage metrics

✨ | This feature requires the use of JaCoCo version 0.6.3 or higher.

The JacocoCoverageVerification task can be used to verify if code coverage metrics are met based on configured rules. Its API exposes the method JacocoCoverageVerification.violationRules(org.gradle.api.Action) which is used as main entry point for configuring rules. Invoking any of those methods returns an instance of JacocoViolationRulesContainer providing extensive configuration options. The build fails if any of the configured rules are not met. JaCoCo only reports the first violated rule.

Code coverage requirements can be specified for a project as a whole, for individual files, and for particular JaCoCo-specific types of coverage, e.g., lines covered or branches covered. The following example describes the syntax.

Example 4. Configuring violation rules
build.gradle

    jacocoTestCoverageVerification {
        violationRules {
            rule {
                limit {
                    minimum = 0.5
                }
            }

            rule {
                enabled = false
                element = 'CLASS'
                includes = ['org.gradle.*']

                limit {
                    counter = 'LINE'
                    value = 'TOTALCOUNT'
                    maximum = 0.3
                }
            }
        }
    }

build.gradle.kts

    tasks.jacocoTestCoverageVerification {
        violationRules {
            rule {
                limit {
                    minimum = "0.5".toBigDecimal()
                }
            }

            rule {
                enabled = false
                element = "CLASS"
                includes = listOf("org.gradle.*")

                limit {
                    counter = "LINE"
                    value = "TOTALCOUNT"
                    maximum = "0.3".toBigDecimal()
                }
            }
        }
    }

✨ | The code for this example can be found at `samples/testing/jacoco/quickstart` in the ‘-all’ distribution of Gradle.

The JacocoCoverageVerification task is not a task dependency of the `check` task provided by the Java plugin. There is a good reason for it. The task is currently not incremental as it doesn’t declare any outputs. Any violation of the declared rules would automatically result in a failed build when executing the `check` task. This behavior might not be desirable for all users. Future versions of Gradle might change the behavior.

## JaCoCo specific task configuration

The JaCoCo plugin adds a JacocoTaskExtension extension to all tasks of type Test. This extension allows the configuration of the JaCoCo specific properties of the test task.

Example 5. Configuring test task
build.gradle

    test {
        jacoco {
            destinationFile = file("$buildDir/jacoco/jacocoTest.exec")
            classDumpDir = file("$buildDir/jacoco/classpathdumps")
        }
    }

build.gradle.kts

    tasks.test {
        extensions.configure(JacocoTaskExtension::class) {
            destinationFile = file("$buildDir/jacoco/jacocoTest.exec")
            classDumpDir = file("$buildDir/jacoco/classpathdumps")
        }
    }

✨ | Tasks configured for running with the JaCoCo agent delete the destination file for the execution data when the task starts executing. This ensures that no stale coverage data is present in the execution data.

### Default values of the JaCoCo Task extension

    test {
        jacoco {
            enabled = true
            destinationFile = file("$buildDir/jacoco/$name.exec")
            includes = []
            excludes = []
            excludeClassLoaders = []
            includeNoLocationClasses = false
            sessionId = "<auto-generated value>"
            dumpOnExit = true
            classDumpDir = null
            output = Output.FILE
            address = "localhost"
            port = 6300
            jmx = false
        }
    }

    tasks.getByName<Test>("test") {
        extensions.configure<JacocoTaskExtension::class) {
            isEnabled = true
            destinationFile = file("$buildDir/jacoco/$name.exec")
            includes = listOf()
            excludes = listOf()
            excludeClassLoaders = listOf()
            isIncludeNoLocationClasses = false
            sessionId = "<auto-generated value>"
            isDumpOnExit = true
            classDumpDir = null
            output = JacocoTaskExtension.Output.FILE
            address = "localhost"
            port = 6300
            isJmx = false
        }
    }

While all tasks of type Test are automatically enhanced to provide coverage information when the `java` plugin has been applied, any task that implements JavaForkOptions can be enhanced by the JaCoCo plugin. That is, any task that forks Java processes can be used to generate coverage information.

For example you can configure your build to generate code coverage using the `application` plugin.

Example 6. Using application plugin to generate code coverage data
build.gradle

    plugins {
        id 'application'
        id 'jacoco'
    }

    application {
        mainClassName = 'org.gradle.MyMain'
    }

    jacoco {
        applyTo run
    }

    task applicationCodeCoverageReport(type:JacocoReport) {
        executionData run
        sourceSets sourceSets.main
    }

build.gradle.kts

    plugins {
        application
        jacoco
    }

    application {
        mainClassName = "org.gradle.MyMain"
    }

    jacoco {
        applyTo(tasks.run.get())
    }

    tasks.register<JacocoReport>("applicationCodeCoverageReport") {
        executionData(tasks.run.get())
        sourceSets(sourceSets.main.get())
    }

✨ | The code for this example can be found at `samples/testing/jacoco/application` in the ‘-all’ distribution of Gradle.

Coverage reports generated by applicationCodeCoverageReport

    .
    └── build
        ├── jacoco
        │   └── run.exec
        └── reports
            └── jacoco
                └── applicationCodeCoverageReport
                    └── html
                        └── index.html

## Tasks

For projects that also apply the Java Plugin, the JaCoCo plugin automatically adds the following tasks:

`jacocoTestReport` — JacocoReport

  Generates code coverage report for the test task.

`jacocoTestCoverageVerification` — JacocoCoverageVerification

  Verifies code coverage metrics based on specified rules for the test task.

## Dependency management

The JaCoCo plugin adds the following dependency configurations:

Table 2. JaCoCo plugin - dependency configurations
Name | Meaning
--- | ---
`jacocoAnt` | The JaCoCo Ant library used for running the `JacocoReport`, `JacocoMerge` and `JacocoCoverageVerification` tasks.
`jacocoAgent` | The JaCoCo agent library used for instrumenting the code under test.