Code Coverage of Robolectric Tests using JaCoCo

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.

Advertisements
This entry was posted in android, maven, open source, serenity, testing. Bookmark the permalink.

2 Responses to Code Coverage of Robolectric Tests using JaCoCo

  1. Alex says:

    I’m trying to use it with Roboelectric tests. I can generate the reports using this, thanks but I can see that the code coverage is always 0. I’m guessing there is a way to include it after we run the tests ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s