android - 如何从测试覆盖范围中排除 Dagger2 类

标签 android android-studio android-testing jacoco dagger-2

是否有任何选项可以从 Android Studio 的测试覆盖率报告中排除 Dagger2 类

最佳答案

JaCoCo 排除

如果您使用的是 JaCoCo,例如使用 android 仪器连接测试,则需要配置排除(或包含),根据 documentation 是...

A list of class files to exclude from the report. May use wildcard characters (* and ?). When not specified nothing will be excluded.

这意味着您需要匹配生成的 Dagger 类名称。以下规则几乎涵盖了 dagger-compiler 生成的任何类,而不匹配任何非生成的类(除非您将类命名为与 dagger 相同...):

excludes = [
    '**/*_MembersInjector.class',
    '**/Dagger*Component.class', // covers component implementations
    '**/Dagger*Component$Builder.class', // covers component builders
    '**/*Module_*Factory.class'
]

运行构建后,您可以在 app/build/generated/source/apt 目录中检查生成的 dagger 类,以查看是否有任何其他要与排除匹配的生成类。

这个排除数组是jacoco插件的配置属性。现在,将这个 excludes 数组放在哪里取决于您是基于 jacoco 插件定义自己的任务,还是使用为您执行此操作的“更高级别的插件”。例如使用 this plugin (您可以查看插件源代码以查看排除的实际应用位置):

jacocoAndroidUnitTestReport {
  excludes +=  [
        '**/*_MembersInjector.class',
        '**/Dagger*Component.class',
        '**/Dagger*Component$Builder.class',
        '**/*Module_*Factory.class'
    ]
}

连接测试

如果您通过在 buildType 中设置 testCoverageEnabled true 来运行 Android 连接测试覆盖率,遗憾的是没有惯用的方式来声明排除 ,因为 android gradle plugin 不提供此类选项,并且预定义的 jacoco report task 已硬编码排除。在这种情况下,您必须使用排除编写自己的任务脚本。

<小时/>

IntelliJ 测试运行程序

如果您使用 IntelliJ 测试运行程序,无论覆盖率是由 IntelliJ 还是 JaCoCo 完成,您都需要为测试配置添加包含

  1. 打开编辑配置窗口:

Edit Configurations

  • 选择您的测试配置并定义包含(类或整个包)。在本例中,我包含了整个 com.google.android.gms 包,仅作为示例:
  • Test coverage includes

    排除 dagger 生成的文件,最快的方法是将所有 dagger 依赖项放入一个根包中,并包含所有其他测试配置中的包。

    关于android - 如何从测试覆盖范围中排除 Dagger2 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42575867/

    相关文章:

    Android源码导航

    java - XmlResourceParser.getText() 在单引号字符后删除文本,忽略双引号

    android - 如何在 Android 的通知中打开浏览器?

    android - 如何使用 MediaMuxerTest(AndroidTestCase 文件)

    android - 如何使用屏幕上的位置(边界)在 UiAutomator 中查找对象

    java - LogCat 中断言和断言过滤器的用途及其用途以及为什么它与 Log.e() 不同?

    Android从后台堆栈中删除 Activity

    android - 错误 :Execution failed for task ':app:mockableAndroidJar' . > java.util.zip.ZipException: invalid entry crc-32 (expected 0x3950d9fc but got 0x12b44089)

    android - 将 jar 作为库添加到 Android Studio,错误 : More than one file was found with OS independent path 'META-INF/DEPENDENCIES'

    android-studio - 未找到 Android SDK 找不到 SDK 工具目录