Thomas Vervik
Thomas Vervik

Reputation: 4535

Run single test to check code coverage Jacoco Android

I'm using ./gradlew createDebugCoverageReport to generate a code coverage report of all my Android instrumentation (Robotium) tests. But I need to run all tests in order to get the coverage report now. How can I specify one single test (or single test class) to execute and get the coverage report? I beed it during development of the tests, it's too slow having to run all tests at once.

Upvotes: 21

Views: 2431

Answers (1)

Cheolho Jeon
Cheolho Jeon

Reputation: 471

I know this is an old post, but here's how I do it.

1. First install the instrumentation test app if you have not.

(Flavor may vary. In this case, it's debug.)

// install instrumentation test app if you have not
./gradlew installDebugAndroidTest

2. Execute a test you want (or tests, classes, packages ..).

In my case, I chose ClassName#methodName.

// execute one test
adb shell am instrument -w -r --no_window_animation -e coverageFile /data/data/com.org.android.test/coverage.ec -e class 'com.org.android.ClassName#methodName', -e coverage true com.org.android.test/android.support.test.runner.AndroidJUnitRunner

Note that I'm passing 2 parameters:

A. -e coverageFile /data/data/com.org.android.test/coverage.ec and,

B. -e coverage true

The two options would generate a coverage report within the device.

If you are not familiar with running tests by adb shell am command, please refer to this official documentation.

3. Then get the coverage.ec file from the device.

// get coverage.ec data
adb shell run-as com.org.android.test  cat /data/data/com.org.android.test/coverage.ec | cat > [YOUR_PROJECT_DIRECTORY]/build/outputs/code_coverage/debugAndroidTest/connected/coverage.exec

There are two things to note here.

A. You should change [YOUR_PROJECT_DIRECTORY] to your project directory. Or, you can change the entire [YOUR_PROJECT_DIRECTORY]/build/outputs/code_coverage/debugAndroidTest/connected/coverage.exec to any directory and filename you want. (maybe desktop?)

B. but the final content should have extension .exec, because jacoco will only accept those.

4. Then view the coverage report using Android Studio.

In Android Studio, please navigate to run > Show Code Coverage Data. Then a select window will appear. Select previously generated coverage.exec. Then the Android Studio will process the data and show you the coverage data. You can directly view the code coverage data, or further generate coverage report.

Upvotes: 2

Related Questions