Android automatic and manual testing using Jacoco

  1. First install Android Studio and import an working Android project
  2. Configure build gradle
apply plugin: jacoco
jacoco{
toolVersion = “0.8.1” // try a newer version if you can
}
debug {
testCoverageEnabled = true
}
task jacocoTestReport(type:JacocoReport) {
group = "Reporting"
description = "Generate Jacoco coverage reports"
// exclude auto-generated classes and tests
def fileFilter = ['**/R.class', '**/R$*.class',
'**/BuildConfig.*', '**/Manifest*.*',
'android/**/*.*']
def debugTree = fileTree(dir:
"${project.buildDir}/intermediates/classes/debug",
excludes: fileFilter)
def mainSrc = "${project.projectDir}/src/main/java"
sourceDirectories = files([mainSrc])
classDirectories = files([debugTree])
additionalSourceDirs = files([
"${buildDir}/generated/source/buildConfig/debug",
"${buildDir}/generated/source/r/debug"
])
executionData = fileTree(dir: project.projectDir, includes:
['**/*.exec', '**/*.ec'])
reports {
xml.enabled = true
xml.destination = "${buildDir}/jacocoTestReport.xml"
csv.enabled = false
html.enabled = true
html.destination = "${buildDir}/reports/jacoco"
}
./gradlew jacocoTestReport
public class JacocoReportGenerator {
static void generateCoverageReport() {
String TAG = "jacoco";
// use reflection to call emma dump coverage method, to avoid
// always statically compiling against emma jar
Log.d("StorageSt", Environment.getExternalStorageState());
String coverageFilePath = Environment.getExternalStorageDirectory() + File.separator + "coverage.exec";
File coverageFile = new File(coverageFilePath);
try {
coverageFile.createNewFile();
Class<?> emmaRTClass = Class.forName("com.vladium.emma.rt.RT");
Method dumpCoverageMethod = emmaRTClass.getMethod("dumpCoverageData",
coverageFile.getClass(), boolean.class, boolean.class);

dumpCoverageMethod.invoke(null, coverageFile, false, false);
Log.e(TAG, "generateCoverageReport: ok");
} catch (Exception e) {
throw new RuntimeException("Is emma jar on classpath?", e)
}
}
}
adb pull /sdcard/coverage.exec app/build/outputs/coverage.exec

--

--

Senior Android Engineer @Delivery Hero | Android developer | Kotlin lover | Flutter explorer | Problem Solver

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Md Ali Hossain

Md Ali Hossain

Senior Android Engineer @Delivery Hero | Android developer | Kotlin lover | Flutter explorer | Problem Solver