Unified Code Coverage for Android: Revisited

Rafael Toledo
ProAndroidDev
Published in
3 min readFeb 16, 2018

--

My post Setting up a unified coverage report in Android with Jacoco, Robolectric, and Espresso got a lot of readers in the last years but is a bit outdated today. There are some deprecation notes, the JVM tests coverage doesn't work with Android Gradle plugin 3.x, and we have some new tools, like Test Orchestrator.

So… what changed from the last post?

Starting with plugin 3.0.0, now we cannot configure Jacoco using the android block DSL. But, on the other hand, we can now force the Jacoco version used when running instrumented tests. So, the first "big change" is to add the new Jacoco version in the classpath dependencies, alongside the Android plugin:

Note the presence of the Google repositories — I also migrated the project to use the (current) latest version of Gradle, 4.5.1.

In the app build.gradle file, right after applying the Jacoco plugin, I set its version, matching the version we applied in the root build.gradle file.

Here we have another trick: since the Jacoco options inside the android node in the DSL have no effect anymore, to enable the includeNoLocationClasses option, we need to change the test tasks. So, we search all the tasks with the Test type, and enable it! :)

Our jacocoTestReport task continues exactly the same from the previous post:

In the android configuration node, I updated the tooling to everything new (API 27, removed the buildTools version — not needed anymore), and changed the testOptions. First, I enabled Android Test Orchestration to make our instrumented tests execution more reliable, disabled the animations during the test execution, and enabled the Android resources for the unit tests — otherwise, the Robolectric tests will fail!

The dependencies are still the same, just updated to latest. I also changed the dependency style to match the 3.x, using implementation instead of compile.

Our test code didn't change so much. I just removed the @Config annotation from the Robolectric test, as it isn't needed anymore.

Aaaaaand, that's it! Enjoy the unified coverage report working with Android plugin 3.x and using the latest version of Jacoco!

How about Kotlin?

Kotlin is here to stay. To enable the coverage on Kotlin, there are some minor tweaks — just change the location of the source files and class files.

The final report for Kotlin correctly displays the visited branches, but when listing the classes, the lambdas are shown as classes.

Branches visited during the tests
Final Kotlin coverage report

The repository with the full code is available here, with the Kotlin code coverage in the kotlin-coverage branch.

EDIT: There’s an open issue related to Orchestrator not generating the properly coverage data. Star the issue and follow it for updates!

--

--