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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import android.os.Bundle; import android.support.test.runner.AndroidJUnitRunner; import android.util.Log; import java.io.IOException; import java.lang.reflect.Method; import java.nio.charset.Charset; public class AndroidJacocoTestRunner extends AndroidJUnitRunner { private static final Charset UTF8 = Charset.forName("UTF-8"); static { // System.setProperty("jacoco-agent.destfile", "/sdcard/coverage.ec"); } @Override public void finish(int resultCode, Bundle results) { try { Class rt = Class.forName("org.jacoco.agent.rt.RT"); Method getAgent = rt.getMethod("getAgent"); Method dump = getAgent.getReturnType().getMethod("dump", boolean.class); Object agent = getAgent.invoke(null); dump.invoke(agent, false); } catch (Throwable e) { final String trace = Log.getStackTraceString(e); try { System.out.write(trace.getBytes(UTF8)); } catch (IOException ignored) { } } super.finish(resultCode, results); } } |
1 2 3 4 5 6 |
testInstrumentationRunner "com.example.anuja.myapplication1.AndroidJacocoTestRunner" also add code given below in buidTypes. debug { testCoverageEnabled = rue } |