简体   繁体   English

android studio中的Jacoco代码覆盖率

[英]Jacoco Code Coverage in android studio

I am trying to generate Jacoco code coverage report.我正在尝试生成 Jacoco 代码覆盖率报告。 I have used AndroidTestCase for my test classes.我已将 AndroidTestCase 用于我的测试类。

I have found using testCoverageEnabled true and using default android -studio default jacoco, ./gradlew connectedCheck or createDebugCoverageReport create the percentage of successfull/fail test cases, but no coverage report.我发现使用 testCoverageEnabled true 并使用默认 android -studio 默认 jacoco、./gradlew connectedCheck 或 createDebugCoverageReport 创建成功/失败测试用例的百分比,但没有覆盖率报告。

Then I have tried jacoco {toolVersion "0.7.1.201405082137"}, and task jacocoTestReport(type:JacocoReport, dependsOn: "testDebug").然后我尝试了 jacoco {toolVersion "0.7.1.201405082137"} 和任务 jacocoTestReport(type:JacocoReport, dependsOn: "testDebug")。 I have tried to change the dependsOn value with various task.我试图通过各种任务更改dependsOn 值。 The report shows 0 (zero) test coverage, which is impossible because at least half of all classes are tested.该报告显示 0(零)测试覆盖率,这是不可能的,因为所有类中至少有一半经过测试。

I have followed various accepted answer of stack overflow in last couple of days.在过去的几天里,我遵循了各种公认的堆栈溢出答案。 The result is negative.结果是否定的。

My gradle file:我的 gradle 文件:

buildscript {
    repositories {
        mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'        
    }
}

apply plugin: 'com.android.application'
apply plugin: 'jacoco'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "test.gradle.com.myapplicationtestgradle"
        minSdkVersion 21
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false            
            proguardFiles getDefaultProguardFile(
            'proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            testCoverageEnabled true
        }
    }

    jacoco {
        version "0.7.1.201405082137"
    }

    packagingOptions {
        exclude 'LICENSE.txt'
    }
}


jacoco {
    toolVersion "0.7.1.201405082137"
}

task jacocoTestReport(type:JacocoReport, dependsOn: "testDebug") {
    group = "Reporting"

    description = "Generate Jacoco coverage reports"

   // exclude auto-generated classes and tests
    def fileFilter = ['**/R.class', '**/R$*.class', 
    '**/BuildConfig.*', '**/Manifest*.*',           
     'android/**/*.*']
    def debugTree = fileTree(dir:   
    "${project.buildDir}/intermediates/classes/debug", 
    excludes: fileFilter)
    def mainSrc = "${project.projectDir}/src/main/java"

    sourceDirectories = files([mainSrc])
    classDirectories = files([debugTree])
    additionalSourceDirs = files([
            "${buildDir}/generated/source/buildConfig/debug",
            "${buildDir}/generated/source/r/debug"
    ])
    executionData = fileTree(dir: project.projectDir, includes: 
                    ['**/*.exec', '**/*.ec'])

    reports {
        xml.enabled = true
        xml.destination = "${buildDir}/jacocoTestReport.xml"
        csv.enabled = false
        html.enabled = true
        html.destination = "${buildDir}/reports/jacoco"
    }
}


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('junit:junit:4.11') {
        exclude module: 'hamcrest-core'
    }
}

Gradle already has built-in support for generating test coverage reports and we don't need to create any additional configurations or add any plugins to generate test coverage report. Gradle 已经内置支持生成测试覆盖率报告,我们不需要创建任何额外的配置或添加任何插件来生成测试覆盖率报告。 Basically, the only thing we need to do is to set testCoverageEnabled parameter to true in build.gradle file as follows:基本上,我们唯一需要做的就是在build.gradle文件中将testCoverageEnabled参数设置为true ,如下所示:

android {
   buildTypes {
      debug {
         testCoverageEnabled = true
      }
   }
}

Next, we can execute the following Gradle task from CLI:接下来,我们可以从 CLI 执行以下 Gradle 任务:

./gradlew createDebugCoverageReport

On Windows, we can execute it like this:在 Windows 上,我们可以这样执行:

gradlew.bat createDebugCoverageReport

Task will analyze code of our project in /src/main/java/ directory and unit tests placed in /src/androidTest/java/ directory.任务将分析/src/main/java/目录中我们项目的代码和放置在/src/androidTest/java/目录中的单元测试。 After executing this task, we can find test coverage report in the following directory of the module:执行此任务后,我们可以在模块的以下目录中找到测试覆盖率报告:

/build/outputs/reports/coverage/debug/

When we open index.html file, we can see a visual report from test coverage, which can be viewed in a web browser.当我们打开index.html文件时,我们可以看到测试覆盖率的可视化报告,可以在 Web 浏览器中查看。

It looks as on the image below.它看起来如下图所示。

在此处输入图片说明

I've written an article about test coverage report in Android application and published it on my blog some time ago.我写了一篇关于Android应用程序测试覆盖率报告的文章,前段时间在我的博客上发表过。 If you are interested in that topic, you can read it at:如果您对该主题感兴趣,可以在以下位置阅读:

Update (Unit test coverage for Robolectric tests)更新(Robolectric 测试的单元测试覆盖率)

If you would like to create test coverage report from unit tests written with Robolectric and generate test coverage report with Jacoco , Travis CI and Codecov.io , please take a look at the new article on my blog:如果您想从使用Robolectric编写的单元测试创​​建测试覆盖率报告并使用JacocoTravis CICodecov.io生成测试覆盖率报告,请查看我博客上的新文章:

I see that you already got it working, however, there's a simpler method for getting Unit Test execution data.我看到你已经让它工作了,但是,有一个更简单的方法来获取单元测试执行数据。 I recently was looking into this as well, I actually made a full write up earlier today .我最近也在研究这个,实际上我今天早些时候写了一篇完整的文章。

In my situation, I didn't want to create an additional Gradle task as I wanted the report to be generated as a part of the existing workflow.在我的情况下,我不想创建额外的 Gradle 任务,因为我希望生成报告作为现有工作流程的一部分。 I also didn't want to explicitly add the Jacoco plugin, as Google already dups the Jacoco Ant tasks for the coverage reports for Instrumentation Tests.我也不想明确添加 Jacoco 插件,因为Google 已经为 Instrumentation Tests 的覆盖率报告复制了 Jacoco Ant 任务。

In addition to setting the properties android.jacoco.version and buildTypes.debug.testCoverageEnabled , I added the following to the testDebug JVM arguments to generate execution data:除了设置属性android.jacoco.versionbuildTypes.debug.testCoverageEnabled ,我testDebug JVM 参数中添加了以下内容以生成执行数据:

project.afterEvaluate {
  def append = "append=true"
  def destFile = "destfile=$buildDir/outputs/code-coverage/connected/coverage.ec"
  testDebug.jvmArgs "-javaagent:$buildDir/intermediates/jacoco/jacocoagent.jar=$append,$destFile"

  createDebugCoverageReport.dependsOn testDebug
}

This appends the Unit Test execution data to the coverage file generated by connectedAndroidTest , so your report reflects both Instrumentation Tests and Unit Tests, rather than each variant individually.这会将单元测试执行数据附加到由connectedAndroidTest生成的覆盖文件中,因此您的报告会同时反映仪器测试和单元测试,而不是单独反映每个变体。

Note that connectedAndroidTest overwrites the coverage file, take this into account when creating your report.请注意, connectedAndroidTest覆盖覆盖率文件,创建报告时要考虑到这一点。 If the task testDebug doesn't have any changes, and you run createDebugCoverageReport , it will only reflect your Instrumentation Test coverage.如果任务testDebug没有任何更改,并且您运行createDebugCoverageReport ,它只会反映您的 Instrumentation Test 覆盖率。 So, make a change to your Unit Tests.因此,对您的单元测试进行更改。 The Linux command touch may be useful here, although I haven't tried yet. Linux 命令touch在这里可能很有用,尽管我还没有尝试过。

Today I did completely removed android studio, android sdk, gradle.今天我确实彻底删除了android studio、android sdk、gradle。 Then reinstall everything.然后重新安装一切。 After that, I just added inside the app build.gradle.之后,我只是在 app build.gradle 里面添加了。

debug {
    testCoverageEnabled true
}

Then I run ./gradlew connectedChec.然后我运行 ./gradlew connectedCheck。 Everything is working perfectly.一切正常。 Android studio default Jacoco working fine for me. Android Studio 默认的 Jacoco 对我来说很好用。 I think it is also possible to create a jacocoTestReport Task and then create code coverage.I don't know why gradle and android studio was not working previously.我认为也可以创建一个jacocoTestReport Task然后创建代码覆盖率。我不知道为什么gradle和android studio以前不起作用。

i investigated correct way to get merged code coverage report with Jacoco, you can check it here: https://gist.github.com/ultraon/54cca81ca159ed0a4a9ebf62e89c26ba我调查了与 Jacoco 合并代码覆盖率报告的正确方法,您可以在这里查看: https ://gist.github.com/ultraon/54cca81ca159ed0a4a9ebf62e89c26ba

I used AndroidStudio 2.2.2 with Gradle 3.2 and Android Gradle Plugin 2.2.2我将 AndroidStudio 2.2.2 与 Gradle 3.2 和 Android Gradle Plugin 2.2.2 一起使用

I had the same problem too, but I made a mistake in the process which took a few days to track down.我也遇到了同样的问题,但是我在这个过程中犯了一个错误,花了几天时间才找到。 Here's my technique and the gotcha that caused the 0% coverage.这是我的技术和导致 0% 覆盖率的问题。

  1. Install jacoco.安装雅可可。 I used the technique described in great detail here with a few modifications because of my project's structure.由于我的项目结构,我使用了此处详细描述的技术,并进行了一些修改。 Thank you Ashish Uniyal!谢谢Ashish Uniyal!

  2. Run jacoco.运行雅可可。 Open the Gradle window in Android Studio (View -> Tool Windows -> Gradle), click on the elephant icon to "Execute Gradle Task." Open the Gradle window in Android Studio (View -> Tool Windows -> Gradle), click on the elephant icon to "Execute Gradle Task."
    在此处输入图像描述

If a pop-up to your settings occurs, go ahead and disable the "Do not build Gradle task list during Gradle sync."如果您的设置出现弹出窗口,请提前 go 并禁用“在 Gradle 同步期间不要构建 Gradle 任务列表”。

In the text window that pops up after clicking the elephant icon, type in: gradle app:createDebugUnitTestCoverageReport and hit [Enter].在单击大象图标后弹出的文本 window 中,输入: gradle app:createDebugUnitTestCoverageReport并按 [Enter]。 在此处输入图像描述 If you want to do AndroidTests, type gradle app:createDebugAndroidTestCoverageReport .如果你想做 AndroidTests,输入gradle app:createDebugAndroidTestCoverageReport

It'll take several seconds to a few minutes to execute jacoco.执行 jacoco 需要几秒钟到几分钟的时间。

  1. Find the results.查找结果。 This can vary depending on your settings in the jacoco.gradle file.这取决于您在 jacoco.gradle 文件中的设置。 But generally you can find the results an index.html file here: ./app/build/reports/coverage/test/debug/index.html .但通常您可以在此处找到 index.html 文件的结果: ./app/build/reports/coverage/test/debug/index.html

My big gotcha was that I typed in the AndroidTest instead of the UnitTest (thank you auto-complete, sigh).我最大的问题是我输入了 AndroidTest 而不是 UnitTest(谢谢自动完成,叹息)。 Since I only did unit testing all jacoco could see was a big fat 0%.因为我只进行了单元测试,所以 jacoco 能看到的只是一个大胖子 0%。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM