Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code coverage in android studio 1.2 for instrumented tests

I have been trying to use the new code coverage feature in Android Studio 1.2. There seems to be no documentation for the feature, but so far I figured out to add

    testCoverageEnabled true

to the debug flavor of my Gradle file.

Still I can only create code coverage reports for JUnit test cases, not instrumented Android test cases.

Is there any way to generate code coverage for instrumented android test cases ?

like image 575
Till Krempel Avatar asked May 11 '15 11:05

Till Krempel


People also ask

How do I run test coverage on Android?

To run tests with coverage, follow the same steps as described in Run tests, only instead of clicking Run , click Run test-name with coverage . In the Project window, this option might be hidden behind More Run/Debug.

What is instrumentation in code coverage?

Computing the source code lines that were executed during the test is done through code coverage. Code coverage requires inserting additional counters into your source code before running it. This step is called instrumentation.

What is instrumented test Android?

Instrumented tests run on Android devices, whether physical or emulated. As such, they can take advantage of the Android framework APIs. Instrumented tests therefore provide more fidelity than local tests, though they run much more slowly.

What should you annotate your test class with in instrumented tests?

Create an Instrumented Unit Test Class To create an instrumented JUnit 4 test class, add the @RunWith(AndroidJUnit4. class) annotation at the beginning of your test class definition. You also need to specify the AndroidJUnitRunner class provided in the Android Testing Support Library as your default test runner.


1 Answers

  1. Add plugins.gradle repository

In the project build.gradle file (root/build.gradle) add url "https://plugins.gradle.org/m2/" under the buildscript > repositories sections. In my project is looks like this:

buildscript {
  repositories {
    mavenCentral()
    jcenter()
    maven {
        url "https://plugins.gradle.org/m2/"
    }
}
  1. Apply jacoco plugin

The plugin can be applied in the project build.gradle or (as in my case) to the specific module's build.gradle (module/build.gradle):

apply plugin: 'com.vanniktech.android.junit.jacoco'

Apply the plugin at the very top of the build script before you enter the android section.

  1. Sync Now when prompted.
  2. Run gradlew connectedCheck

From the Terminal run:

Windows

gradlew.bat connectedCheck

Linux (other)

./gradlew connectedCheck
  1. The results will be created in /module/build/reports/androidTests/connected/index.html

References:

https://plugins.gradle.org/plugin/com.vanniktech.android.junit.jacoco https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/

like image 72
Malba Avatar answered Oct 02 '22 13:10

Malba