Android Tips: Generating a coverage report for your unit tests

The Android testing framework has the built-in ability to generate a code coverage report for your unit tests. Unfortunately this functionality is not available within the Eclipse IDE, so you have to resort to some command line and Ant fu.

First off, you need to create a test project for your Android app and some unit tests.

Next, run the following command:

android update test-project -m <path to app project> -p <path to test project>

This will create a Ant build.xml file in your test project’s top-level directory. The android tool can be found in the tools folder of your SDK installation.

Now, from your test projects top-level directory, run the following command:

ant coverage

This will build, instrument, deploy and run your unit tests. It will also generate a HTML coverage report.

The location of the report will be displayed in the last few lines of the Ant script’s output. Point a web browser at the coverage report and weep :)

UPDATE: if you are using SDK 14 or later then the command to run is now:

ant emma debug install test

See the SDK Ant command reference for more details