Android Unit Test Coverage Check

Michael Febrianto
3 min readMar 3, 2023

--

Photo by Dan Lohmar on Unsplash

Unit test and software development is inseparable. The lack of unit test make integrity of application cannot be confirmed.

It’s like handing pilots a plane we’re not sure will fly or not. Let’s assume that the unit test is in place and that we have successfully tested the plane’s ability to fly. The plane, however, cannot be opened after landing since we lack a coverage check of the unit test.

I find that writing unit tests actually increases my programming speed.

— Martin Fowler

Every programming language has their own different way to do unit test coverage check. Android use a library called jacoco to do reporting of tests. It is very useful not for only unit test but also instrumentation test. We would not discuss instrumentation test in this instance but focusing only on unit test coverage report and check.

Gradle and Jacoco

Jacoco is working together with gradle to build coverage report for android unit test. If you check gradle documentation on Jacoco plugin. It seems from documentation it is very easy to generate unit test and coverage report. All you need to do is :

unfortunately, that simple configuration above is not enough for android project. It will not work on android project because it needs java plugin which android project does not use.

Even-though the simplest configuration does not work on android project but the updated version of gradle already has jacoco built-in. So you do not need to add jacoco dependency manually like this :

Unless you are using gradle version 2.12 and below which I strongly suggest to upgrade. Once again, please do not add example shown above.

Unit Test Coverage Report

Open your module build.gradle and put in the task describe below

Sync your project with the updated version of the build.gradle then you will see the new build task on the gradle task list of android studio

If you run this task then you will find the generated report of the unit test result and its coverage. It will look like this:

We have the coverage number. Let’s keep going to put the check in place.

Unit Test Coverage Check

We are going to put Jacoco as our gatekeeper. If the coverage is below our criteria which is in this case 50% then it shall not pass.

Please do not overwhelmed by the number of code. The main configuration here is violationRules set. If the coverage below what you have put in then it will return error like this:

You can call this task in your CI/CD tools then you will sleep better knowing the plane will operating without or at least less issue.

That’s all for now. Hope it’s useful for you. God bless you all.

--

--