如何使用 Android gradle 插件 0.10.0 或更高版本获取 jacoco 覆盖率报告?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23795595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:28:01  来源:igfitidea点击:

How do I get a jacoco coverage report using Android gradle plugin 0.10.0 or higher?

androidunit-testinggradleandroid-gradle-pluginjacoco

提问by Taeho Kim

I'm trying to get a test coverage report using Gradle Android plugin 0.10.2. But I still can't get a coverage report after running some tests. (connectedAndroidTest).

我正在尝试使用 Gradle Android 插件 0.10.2 获取测试覆盖率报告。但是在运行一些测试后我仍然无法获得覆盖率报告。(连接AndroidTest)。

my main module's build.gradle is :

我的主模块的 build.gradle 是:

apply plugin: 'android'

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.3"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        debug {
            testCoverageEnabled true
        }

        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:19.+'
}

and the buildscript section of project's build gradle is :

项目构建 gradle 的 buildscript 部分是:

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

Once I run a gradlew connectedAndroidTestfrom terminal, I can find coverage-instrumented-classesand code-coveragefolder inside the buildfolder. But I can't find coveragefolder in the reportsfolder. (Only I can see is androidTestsfolder)

一旦我运行一个gradlew connectedAndroidTest从终端,我能找到coverage-instrumented-classescode-coverage该文件夹里面build的文件夹。但是我coveragereports文件夹中找不到文件夹。(只有我能看到是androidTests文件夹)

Is there anything missing for getting a jacoco coverage report?

获得 jacoco 覆盖率报告有什么遗漏吗?

回答by Taeho Kim

Over the hundreds of times searching the answer to getting a coverage report, I finally found an exact answer what I want.

经过数百次搜索获得覆盖报告的答案,我终于找到了我想要的确切答案。

From the this blog post, I found that gradlew createDebugCoverageReportcreates the jacoco coverage report.

这篇博客文章中,我发现gradlew createDebugCoverageReport创建了 jacoco 覆盖率报告。

Also, from the gradle plugin source code, the plugin uses jacoco 0.6.2.201302030002 by default. (therefore, jacoco version definition is not requiredif you are going to use a default version)

另外,从 gradle 插件源代码来看,插件默认使用 jacoco 0.6.2.201302030002。(因此,如果您要使用默认版本,则不需要 jacoco 版本定义

In summary, the ESSENTIALsteps to get a jacococoverage report with Android gradle plugin are:

总之,使用 Android gradle 插件获取覆盖率报告的基本步骤jacoco是:

  1. Android gradle plugin version 0.10.0or higher (typically in your project's build.gradle)
  2. add testCoverageEnabled trueto the build type you want (i.e. debug)
  3. run $ gradlew createDebugCoverageReportor gradlew connectedCheckto get a jacococoverage report.
  1. Android gradle 插件版本0.10.0或更高版本(通常在您的项目中build.gradle
  2. 添加testCoverageEnabled true到您想要的构建类型(即debug
  3. 运行$ gradlew createDebugCoverageReportgradlew connectedCheck获取jacoco覆盖率报告。

You can find your coverage report at the build/reports/coverage/{buildType}. (i.e. build/reports/coverage/debugfor debug build)

您可以在build/reports/coverage/{buildType}. (即build/reports/coverage/debug用于调试版本)

(Add multi-flavor case from @odiggity's comment)

(从@odiggity 的评论中添加多口味案例)

If your project uses multi-flavor configuration, use create{flavorName}CoverageReportinstead. The coverage report will be generated at build/reports/coverage/{flavorName}/{buildType}.

如果您的项目使用多口味配置,请create{flavorName}CoverageReport改用。覆盖率报告将在 生成build/reports/coverage/{flavorName}/{buildType}

Example for flavor krInternalwith debugbuild type:

具有调试构建类型的风味krInternal示例:

  • Command: ./gradlew createKrInternalDebugCoverageReport
  • Report is genarated at: build/reports/coverage/krInternal/debug
  • 命令: ./gradlew createKrInternalDebugCoverageReport
  • 报告生成于: build/reports/coverage/krInternal/debug

Tip :

提示 :

Since you can only get a coverage report with the emulatorand device with root permission, you'll get following error after running a command on the regular(non-rooted) device:

由于您只能使用emulatorand获取覆盖率报告,因此device with root permission在常规(非 root 用户)设备上运行命令后会出现以下错误:

05:48:33 E/Device: Error during Sync: Permission denied                         
java.io.IOException: com.android.ddmlib.SyncException: Permission denied
    at com.android.builder.testing.ConnectedDevice.pullFile(ConnectedDevice.java:114)
    at com.android.builder.internal.testing.SimpleTestCallable.call(SimpleTestCallable.java:158)
    at com.android.builder.internal.testing.SimpleTestCallable.call(SimpleTestCallable.java:42)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)   
Caused by: com.android.ddmlib.SyncException: Permission denied
    at com.android.ddmlib.SyncService.doPullFile(SyncService.java:511)
    at com.android.ddmlib.SyncService.pullFile(SyncService.java:320)
    at com.android.ddmlib.Device.pullFile(Device.java:849)
    at com.android.builder.testing.ConnectedDevice.pullFile(ConnectedDevice.java:107)
    ... 10 more                
:myDirections:connectedAndroidTest FAILED      

FAILURE: Build failed with an exception.

Travis-CI build script to get code coverage

Travis-CI 构建脚本以获取代码覆盖率

Include this block in build.gradle, for all modules (library, sample, etc)

将此块包含在 build.gradle 中,适用于所有模块(库、示例等)

android {
    lintOptions {
        abortOnError false
    }
}

Below is the .travis-ci.ymlfile

下面是.travis-ci.yml文件

language: android
jdk: oraclejdk8
sudo: required

android:
  components:
  # Uncomment the lines below if you want to
  # use the latest revision of Android SDK Tools
  - tools
  - platform-tools
  # The BuildTools version used by your project
  - build-tools-28.0.3
  # The SDK version used to compile your project
  - android-28
  - android-22
  - add-on
  # Additional components
  - extra-google-google_play_services
  - extra-android-support
  - extra-google-m2repository
  - extra-android-m2repository
  # Specify at least one system image,
  # if you need to run emulator(s) during your tests
  - sys-img-armeabi-v7a-android-22

  licenses:
  - 'android-sdk-preview-license-52d11cd2'
  - 'android-sdk-license-.+'
  - 'google-gdk-license-.+'

before_cache:
- rm -f  $HOME/.gradle/caches/modules-2/modules-2.lock
- rm -fr $HOME/.gradle/caches/*/plugin-resolution/

cache:
  directories:
    - $HOME/.gradle/caches/
    - $HOME/.gradle/wrapper/
    - $HOME/.android/build-cache

before_install:
- yes | sdkmanager "build-tools;28.0.3"

before_script:
- echo no | android create avd --force -n test -t android-22 --abi armeabi-v7a -c 100M
- emulator -avd test -no-audio -no-window &
- android-wait-for-emulator
- sleep 180
- adb devices
- adb shell input keyevent 82 &

script:
- ./gradlew build connectedCheck

after_success:
- bash <(curl -s https://codecov.io/bash)

回答by Niklas

I created an open source pluginfor that.

我为此创建了一个开源插件

Root build.gradle

根构建.gradle

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

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.vanniktech:gradle-android-junit-jacoco-plugin:0.3.0'
    }
}

Then simply execute

然后简单地执行

./gradlew jacocoTestReportDebug // or jacocoTestReportRelease

It'll run the JUnit tests and then give you the Jacoco output in xml and html form in the corresponding build directory for debug build type.

它将运行 JUnit 测试,然后在相应的构建目录中为您提供 xml 和 html 形式的 Jacoco 输出,用于调试构建类型。

回答by Better Shao

Have to add an answer instead of a comment since my reputation is lower than 50...

必须添加答案而不是评论,因为我的声誉低于 50...

What I want to supplement is:

我想补充的是:

Google released new build tools fixing the nasty "VerifyError" (link) issue.

Google 发布了新的构建工具,修复了令人讨厌的“VerifyError”(链接)问题。

Please try to change your setting in gradle to use latest build tools if you encounter the "VerifyError" issue. For instance,

如果遇到“VerifyError”问题,请尝试更改 gradle 中的设置以使用最新的构建工具。例如,

android {
    ......
    buildToolsVersion '21.1.1'
    .....
}

Since the 21.0.0 build tools is buggy, please use a version greater than 21.0.0. I use 21.1.1.

由于 21.0.0 构建工具有问题,请使用大于 21.0.0 的版本。我使用 21.1.1。

回答by nhaarman

If you want to use a different version than the default, then add

如果要使用与默认版本不同的版本,请添加

jacoco {
    version = '0.7.3.201502191951'
}

inside the androidtag in your app's build.gradle.

内部android应用程式的标签build.gradle

One way to find the latest version number: search for "org.jacoco:jacoco" on JCenter.

查找最新版本号的一种方法:在JCenter上搜索“org.jacoco:jacoco” 。

回答by Yuliia Ashomok

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. Basically, the only thing we need to do, is to set testCoverageEnabledparameter to truein build.gradlefile as follows:

Gradle 已经内置支持生成测试覆盖率报告,我们不需要创建任何额外的配置或添加任何插件来生成测试覆盖率报告。基本上,我们唯一需要做的就是在文件中设置testCoverageEnabled参数,如下所示:truebuild.gradle

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. After executing this task, we can find test coverage report in the following directory of the module:

任务将分析/src/main/java/目录中我们项目的代码和放置在/src/androidTest/java/目录中的单元测试。执行此任务后,我们可以在模块的以下目录中找到测试覆盖率报告:

/build/outputs/reports/coverage/debug/

When we open index.htmlfile, we can see visual report from test coverage, which can be viewed in a web browser.

当我们打开index.html文件时,我们可以看到测试覆盖率的可视化报告,可以在 Web 浏览器中查看。

It looks as on the image below.

它看起来如下图所示。

enter image description here

在此处输入图片说明

article about test coverage report in Android application http://blog.wittchen.biz.pl/test-coverage-report-for-android-application/

关于 Android 应用程序中测试覆盖率报告的文章 http://blog.wittchen.biz.pl/test-coverage-report-for-android-application/