Code coverage for Android

What is code coverage and why is it so useful

Code coverage is a visual presentation of which lines of code your unit tests are covering.
This way you have a visual clue of what your tests are covering and, obviously, which parts of the code are not being covered.
You can easily harden your code by writing tests to cover as much code as you can.
However, a line of code that is covered does not means that it is well tested! It just means that at a certain point, your test went through this line.

Code coverage with Android

Several tools can be used to generate code coverage such as JaCoCo (, IntelliJ IDEA ( or Clover ( but one among them is easier to use: Emma ( and comes with Android SDK so you don't need to install any extra stuff.

To generate code coverage you'll need the following prerequisites :
Ant installed and present in your classpath.
An Android emulator or a rooted devices connected to your computer. (Emma needs to be able to write on the device.)
Android SDK

Open a command prompt and then go to your tests project folder. Type :
« ant clean emma debug install test » then press enter.

Once the build is over, you can load the « bin » folder of your tests project, you will find a « coverage.html » file (and a bunch of other related files such as: « coverage.txt », « coverage.xml » and a « _file » folder as well), open it and you should see something like this :

The result is self-explanatory, just click on a class to get more details and see how lines are covered :

A red line is not covered, a yellow one is partially covered (in this example, it means that not all cases are tested), and a green one is covered.

Robotium to improve code coverage

Ok, you did your best but there is still tons of important lines that you can't cover, even using mocks. Those lines are probably used by the UI part of your project so using functional tests can help.
I'm used to Robotium ( which can also work with WebView.
Since Robotium tests are run using Junit, you won't have much to do! Just add a new test class, write your Robotium test, then re-run the same command line as show before.


Even if code coverage is not a final goal to reach, it can helps to spot weak points in the code and allows to fix new objectives (50% of coverage is nice! Aiming at 100% doesn't seem to be realistic and will probably cost you a lot of time that you could spend on improving existing tests on critical part of your code for instance).
Nowadays continuous integration is quite common, adding a coverage report generation to it is an effort that can leads to good practices and should probably be considered for every project.