Those that have followed me over the years know that I’m big proponent of Unit Testing and Code Coverage. When I started working on Serenity for Android as a learning project for Android development, I missed not having that code coverage ability. Fortunately, I found Robolectric which allows for running your Android tests natively without the need for an emulator or device. The tests run within the JVM so that means you can leverage existing Java code testing tools.
I also happen to use Maven for my builds for android as well. Unfortunately, by default the android-maven-plugin will try and use emma, which I’ve found to be buggy when it comes to code coverage. As I’ve used JaCoCo and since Robolectric tests run in the JVM, it seemed natural to try and use JaCoCo.
For those using maven, here is how you can do it.
<plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.6.2.201302030002</version> <executions> <execution> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>report</id> <phase>prepare-package</phase> <goals> <goal>report</goal> </goals> </execution> </executions> <configuration> <includes> <include>us/nineworlds/serenity/*</include> </includes> </configuration> </plugin>
Add the above to pom.xml where you have your Robolectric tests. You will want to update the includes section to have it only include the classes that are relevant to your particular app. Otherwise JaCoCo will complain that it can’t instrument some of the Google Play Services libraries like Google Analytics, and a few others.
Once that is done, you can run your Robolectric tests as normal and you JaCoCo will record the coverage. You can view the resulting reports or use the JaCoCo Jenkins plugin to show the results as part of your continuous integration builds.