Once you start writing tests for your Android projects, it is good to know how much of your code base is covered by tests. There are plenty of test coverage tools for Java, but Jacoco is the most popular one. It is also included by default, which makes it easy to get started.
Enabling coverage reports is very easy. You just need to set testCoverageEnabled = true
on the build type that you are testing. Enable test coverage for the debug build type like this:
buildTypes { debug { testCoverageEnabled = true } }
When you enable test coverage, the coverage reports are created when you execute gradlew connectedCheck
. The task that creates the report itself is createDebugCoverageReport
. Even though it is not documented, and it does not appear in the task list when you run gradlew tasks
, it is possible to run it directly. However, because createCoverageReport
depends on connectedCheck
, you cannot execute them separately. The dependency on connectedCheck
also means that you need a connected device or emulator to generate the test coverage report.
After the task is executed, you can find the coverage report in the app/build/outputs/reports/coverage/debug/index.html
directory. Every build variant has its own directory for reports, because each variant can have different tests. The test coverage report will look something like this:
The report shows a nice overview of the coverage on the class level, and you can click through to get more information. In the most detailed view, you can see which lines are tested, and which ones are not, in a useful color-coded file view.
If you want to specify a particular version of Jacoco, simply add a Jacoco configuration block to the build type, defining the version:
jacoco { toolVersion = "0.7.1.201405082137" }
However, explicitly defining a version is not necessary; Jacoco will work regardless.