Java – Use JaCoCo in Android Project with Gradle

androidbuild-errorgradlejacocojava

I have an android project with Gradle 5.1.1
I want to use JaCoCo to generate HTML reports about test code coverage. I tried to follow the instructions in some articles, but all of my attempts led to errors.

All that worked for me is applying plugin 'jacoco' (Project successfully builded after that).

apply plugin: 'jacoco'

But as soon as i add task 'jacocoTestReport', Gradle cannot sync with files and i get this error.

That's my task:

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

That's my error:

ERROR: Could not find method jacocoTestReport() for arguments [build_8kqk7qvpoocfxfydulk1p4m35$_run_closure3@1aba12a5] on project ':app' of type org.gradle.api.Project.

I tried using "gradlew clean build" after adding "apply plugin" in 'build.gradle'. Author of tutorial successfully added task and used this line in terminal to get jacoco report:

gradlew build jacocoTestReport

Here's links to articles i used to understand how to add jacoco to project:

https://reflectoring.io/jacoco/

https://android.jlelse.eu/get-beautiful-coverage-reports-in-your-android-projects-ce9ba281507f

So my question is: Is there a way to add Jacoco to Android Project with Gradle? What am i doing wrong?

Best Answer

Might just be a missing copy paste, but make sure you define your function as a task in gradle, ie: task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest']) {

I followed this blog for setting my Jacoco instance in my initial projects and found it quite helpful. https://engineering.rallyhealth.com/android/code-coverage/testing/2018/06/04/android-code-coverage.html