top of page

Android Code Coverage with JaCoCo

At Houzz, we use automatic testing to ensure that the Houzz App is stable and bug free. With time, the automation test suite has gotten larger, and more comprehensive. As developers, we wanted to measure how much of our code is being tested and to understand what scenarios are accounted for, which not, and what additional automated testing to add. To do this, we used Code Coverage. It is common practice to use Jacoco on Android, specifically, but it’s integration into Jenkins and a continuous integration system is far from simple.

In this article, I will demonstrate how to integrate code coverage into Jenkins automated continuous integration using a simple Android app. The full code of this post can be found on github.

Simple Demo Project

I made an app that contains a screen with one button. Clicking on the button causes the text to appear.

image

Unit Testing

To test this app, I chose to use the Espresso framework. This framework is the official framework for Android unit testing. Other frameworks that can be used include Robotium and UIAutomator.

The scenario covered by the test is that a click on the “Hello World!” button causes the “I am alive!” text to appear.

Here is the code:

@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {

    @Rule
    public ActivityTestRule mActivityRule = new ActivityTestRule(MainActivity.class);

    @Test
    public void checkButton() { 
        onView(withId(R.id.button)).perform(click());
        onView(withId(R.id.textview)).check(matches(withText(R.string.i_am_alive)));
    }
}

Running this code makes a click on the button and, once the text is verified to match the required test, the text to appear.

Adding Code Coverage

Now for the code coverage. To add the code coverage to the app we need to add this line to the build.gradle:

buildTypes {
    debug {          
        testCoverageEnabled true
    }
}