How to get code coverage using Android Studio?
Asked Answered
A

10

82

I am developing apps using Android Studio.
I was able to run the test code.
But, I do not know how to get code coverage in android studio.

I have already seen the following links.
Android Gradle Code Coverage
But I can't wait for update to v0.6 supporting emma.

Project configuration is as follows.

Main code
MyProject/AppName/src/main/java/mypackage/MyClass.java

Test code
MyProject/AppName/src/instrumentTest/java/mypackage/test/MyClassTest.java

Project configuration
MyProject
├─build.gradle
└─AppName
    ├─build.gradle
    └─src
        ├─main
        │  ├─java
        │  │  └─mypackage
        │  │      └─MyClass.java
        │  ├─res
        │  └─AndroidManifest.xml
        └─instrumentTest
            └─java
                └─mypackage
                    └─test
                        └─MyClassTest.java

Airt answered 8/9, 2013 at 11:14 Comment(1)
Wish they had this, it was really nice in Eclipse. Easier to see what you missed.Alarmist
E
68

With the new Android Studio 1.2, you are able to run your unit tests and see the coverage all within the IDE.

First, you'll need to get your unit tests running in the IDE. (if you already can, then skip this step)

This guide and demo will help you.

Secondly, you'll need to create a JUnit Run configuration

enter image description here

Inside this configuraiton, you'll be able to choose

  • Test Kind: "All in Package"
  • Package: [the package where your tests reside, eg: "com.myapp.tests"]
  • Search for tests: Across Module Dependencies (could be diff for your setup)
  • VM -options: -ea
  • Working Directory: [your project's directory]
  • Use classpath of mod: [select your module]

If you have any issue creating your JUnit Run Configuration, you should visit this guide for help.

Lastly, in the latest Android Studio, you should be able to run your JUnit-Run Configuration by clicking on the 'Run with Coverage' button.


In Android Studio 2.1.3 the is label Run Unit tests with Coverage where Unit test is the name of your test configuration as shown in the following screenshot:

Android Studio: "Run Unit tests with Coverage" button

Encomiast answered 11/5, 2015 at 21:8 Comment(3)
Great answer, the 'Run with Coverage' button is key and sits to the right of the 'Debug' button by default.Lacey
To do this via the command line, you would most likely need to use a tool like JaCoCo. docs.gradle.org/current/userguide/jacoco_plugin.html would be a good place to start.Encomiast
so how do we actually see the coverage/coverage report?Southbound
C
45

There are so much answers showing how to apply jacoco plugin to Android studio project, which is outdated, and wasted me so much time to figure out the solution for recently Android studio(My Android Studio is version 2.1.2).

  • Jacoco plugin is built in for Android Studio gradle, what you need to do is just enable it like following:
  buildTypes {
    ...
    debug {
      testCoverageEnabled true
    }
  }
  • After you do above, run unit test task ./gradlew testDebugUnitTest

  • Then create coverage files: ./gradlew createDebugCoverageReport

  • Coverage files will be created under <module>/build/reports/coverage/debug folder,include index.html, which you can open it with browser, and report.xml which you can use to get a report by jenkins jacoco plugin or other continues integration tools.

For those who got 0% coverage with jenkins jacoco plugin, be sure to use the right version. quote from their site:

Unfortunately JaCoCo 0.7.5 breaks compatibility to previous binary formats of the jacoco.exec files. The JaCoCo plugin up to version 1.0.19 is based on JaCoCo 0.7.4, thus you cannot use this version with projects which already use JaCoCo 0.7.5 or newer. JaCoCo plugin starting with version 2.0.0 uses JaCoCo 0.7.5 and thus requires also this version to be used in your projects. Please stick to JaCoCo plugin 1.0.19 or lower if you still use JaCoCo 0.7.4 or lower

Chavira answered 1/9, 2016 at 4:50 Comment(3)
I get 0% coverage with the built in Jacoco. Anyone knows how to fix this? (Using gradle 2.2.3)Meritorious
I got 0% on newer Samsung devices, other devices work fine.Skivvy
I got the report under reports/jacoco folderPsyche
M
5

If you want to get your test coverage (for instrumented tests - When the 'Run the app with Coverage' is not enabled):

Put this into your top-level build.gradle:

buildscript{    
       ext.jacocoVersion = '0.8.2'

       ...

        dependencies {
            classpath "org.jacoco:org.jacoco.core:$jacocoVersion"
        }
}

Into your app-level build.gradle:

 ...

    apply plugin: 'jacoco'

    jacoco {
        toolVersion = "$jacocoVersion"
    }

    tasks.withType(Test) {
        jacoco.includeNoLocationClasses = true
    }

    task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest', 'createDebugCoverageReport']) {

        reports {
            xml.enabled = true
            html.enabled = true
        }

        def fileFilter = [
                '**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*', '**/*Test*.*', 'android/**/*.*', '**/*$[0-9].*'
        ]
        def debugTree = fileTree(dir: "$project.buildDir/tmp/kotlin-classes/debug", excludes: fileFilter)
        def mainSrc = "$project.projectDir/src/main/kotlin"

        sourceDirectories = files([mainSrc])
        classDirectories = files([debugTree])
        executionData = fileTree(dir: project.buildDir, includes: [
                'jacoco/testDebugUnitTest.exec', 'outputs/code_coverage/debugAndroidTest/connected/**/*.ec'
        ])
    }


   android {

        ...

        buildTypes {
            debug {
                testCoverageEnabled true
        }
    }

Then you should write your test, and tests have to passed. If you are sure, your tests passed, write that code into the terminal:

gradlew connectedCheck

It will run your tests. If you did everything right, you should get a report file in app -> build -> reports -> coverage. You have to open the index.html file. (Right click on the file -> Open in Browser -> select a browser)

You should get something similar to this. enter image description here

It's working in my project. Maybe there is a better and easier solution. If I forgot something to write down here, pls write comment.

Margerymarget answered 9/4, 2020 at 15:37 Comment(4)
android.jlelse.eu/…Margerymarget
This process also works for the pure unit tests in app/src/test/. So when you run ./gradlew testDebugUnitTest , it will also run the gradle task "jacocoTestReport" to create a code coverage report. And you don't need to have testCoverageEnabled true in the build.gradle file for the pure unit tests. That's only needed to get coverage for the Instrumentation UI tests.Microchemistry
Additional guidance: proandroiddev.com/… and veskoiliev.com/…Microchemistry
Good One @MargerymargetCreolized
E
3

Enable testCoverage in your module build.gradle file

buildTypes {
        debug {
            testCoverageEnabled true
        }
    }

and then

Right click on the test -> java package and select Run Tests in Java with Coverage to run all tests with code coverage or right click on the particular test class and click Run SampleTest with Coverage

Ebony answered 15/10, 2019 at 16:48 Comment(0)
M
2

Have you tried using the Jacoco plugin for getting code coverage for your project? It is a good plugin giving you coverage based on your package or individual classes. I am not sure how you configure Jacoco to use with Gradle since i use Maven. Check the link: and see if it helps you

Minetta answered 27/12, 2013 at 2:0 Comment(3)
I tried how to set the JaCoCo in Android Studio, but it did not work. I have the same result as follows. #18358797 I checked other, how to set the JaCoCo in Android Studio, but I did not get the solution. stackoverflow.com/search?q=android+jacoco Please tell me if you know how to set the JaCoCo in Android Studio.Airt
@Airt same issue for me. Ping me if you find a solution.Oneiric
gradle.org/docs/current/userguide/jacoco_plugin.html.. this should help you setup jacoco on gradle.Minetta
T
2

We use maven to build our app and cobertura for code coverage reporting

both are really easy to integrate

android maven integration:

http://www.vogella.com/tutorials/AndroidBuildMaven/article.html

Maven + Cobertura Code Coverage Example:

http://www.mkyong.com/qa/maven-cobertura-code-coverage-example/

Thibaud answered 24/4, 2014 at 19:17 Comment(0)
H
2

I don't think you can see visual code coverage report inside Android Studio. But you could try Jacoco. You will need to integrate it in your build.gradle file. You can find the similar question & solution here

Hamburger answered 15/6, 2014 at 15:48 Comment(0)
D
2

Android studio gradle has inbuilt Jacoco plugin which you can use to find code coverage. I have written as article to step by step configure jaococo to find code coverage for Espresso test case but you can use it for Robotium as well. check this out.

http://qaautomated.blogspot.in/2016/03/how-to-find-code-coverage-with-jacoco.html

Disconcert answered 16/3, 2016 at 7:25 Comment(0)
U
1

You can just right click on the package you are curious about and select Run 'Tests in "package" with coverage'

Undercast answered 22/1, 2020 at 12:33 Comment(0)
G
0

For kts (Kotlin) below code will enable unit test code coverage report

getByName("debug") {
            enableAndroidTestCoverage = true
        }
Glaive answered 28/2, 2023 at 11:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.