How to Get Code Coverage with Jacoco and Espresso


Finding code coverage is very important for testing because it allows you to measure your testing efforts. If you have a test suite prepared for your application but you are not sure test suite covers how much percentage of code then finding the code coverage will be good practice Once you get the coverage report, you will know exactly what part of code is not covered in your test case and then you can add test cases to cover the code.

Jacoco is java code coverage tool which allows you to calculate code coverage for your unit tests and instrumented tests. Jacoco can be used with Ant, Maven & Gradle build tools. Today, I will show you step by step integration of Jacoco with Gradle for Espresso test suite.


I have done this setup for Simple Hello world project to give idea of how Jacoco works and gives proper code coverage report.

Pre-requisite –

  • Android Studio
  • Junit
  • Espresso Setup
  • Espresso Test Case written as per our previous post for “Hello Word”

How to Setup Jacoco and Get Coverage ?

    • Create an android project as shown in my previous post.
    • Create a java class inside src->main->androidTest and write your Espresso test case in the class
    • Create a new class named AndroidJococoTestRunner in src -> main ->androidTest and copy below code inside the class.
    • Open app-> build.gradle and copy below code in defaultConfig.
 

    • Then click on Gradle on right side of Android studio -> click on refresh -> other -> right click on createDebugAndroidTestCoverageReport -> click on run

 

    • This action will run all the test cases inside src->main->androidTest and give the report in app->build-> reports ->coverage -> debug.
    • pen index.html file in the browser to check the code coverage report as shown in below screenshot.

Jacoco_Code_Coverage1

 

 






Leave a Reply