Skip to content Skip to sidebar Skip to footer

Android Coverage Launch With Jacoco

We have an Android application that we are building with Gradle/Android Studio and are using JaCoCo to generate code coverage reports for our unit tests; this is working great. We

Solution 1:

apply plugin: 'jacoco'
def coverageSourceDirs = [
        '../app/src/main/java'
]

jacoco{
    toolVersion = "0.7.4.201502262128"
}

task jacocoTestReport(type: JacocoReport) {
    group = "Reporting"
    description = "Generate Jacoco coverage reports after running tests."
    reports {
        xml.enabled = true
        html.enabled = true
    }
    classDirectories = fileTree("enter code here"dir: './build/intermediates/classes/debug',
            excludes: ['**/R*.class',
                       '**/*$InjectAdapter.class',
                       '**/*$ModuleAdapter.class',
                       '**/*$ViewInjector*.class'
            ])
    sourceDirectories = files(coverageSourceDirs)
    executionData = files("$buildDir/outputs/code-coverage/connected/coverage.exec")
    doFirst {
        new File("$buildDir/intermediates/classes/").eachFileRecurse { file ->
            if (file.name.contains('$$')) {
                file.renameTo(file.path.replace('$$', '$'))
            }
        }
    }
}

// this is for the report

debug {
            testCoverageEnabled true
        }

// this is for offline

add these to the build.gradle file.

add directory "resources" to the app>src>main

add jacoco-agent.properties file to resources.

write destfile=/sdcard/coverage.exec to file jacoco-agent.properties

now add this class to your project .

publicclassjacoco {
    staticvoidgenerateCoverageReport() {
        StringTAG="jacoco";
        // use reflection to call emma dump coverage method, to avoid// always statically compiling against emma jarStringcoverageFilePath="/sdcard/coverage.exec";
        java.io.FilecoverageFile=newjava.io.File(coverageFilePath);
        try {
            Class<?> emmaRTClass = Class.forName("com.vladium.emma.rt.RT");
            MethoddumpCoverageMethod= emmaRTClass.getMethod("dumpCoverageData",
                    coverageFile.getClass(), boolean.class, boolean.class);

            dumpCoverageMethod.invoke(null, coverageFile, false, false);
            Log.e(TAG, "generateCoverageReport: ok");
        } catch (Exception  e) {
            newThrowable("Is emma jar on classpath?", e);
        }
    }
}

when your app is onDestroy call the function

jacoco.generateCoverageReport();

you can run your app . when test over you can use command "adb pull /sdcard/coverage.exec yourapp/build/outputs/code-coverage/connected/coverage.exec".

the last operation run gradle task define above there "jacocoTestReport".

ok. all done. open the index.html in "yourapp/build/reports/jacoco/jacocoTestReport/html/".

Post a Comment for "Android Coverage Launch With Jacoco"