How to exclude Dagger2 classes from test coverage

前端 未结 2 1165
感情败类
感情败类 2021-02-18 15:43

Is there any option to exclude Dagger2 classes from test coverage report in Android Studio

2条回答
  •  南笙
    南笙 (楼主)
    2021-02-18 16:30

    JaCoCo excludes

    If you're using JaCoCo, for example using android instrumentation connected tests, you need to configure the excludes (or includes), which, according to the documentation is...

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

    Which means you need to match the generated dagger class names. The following rules cover virtually any class generated by dagger-compiler, without matching any of non-generated classes (unless you name your class the same as dagger does...):

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

    You can check your generated dagger classes in app/build/generated/source/apt directory after running a build, to see if there are any additional generated classes that you want to match with excludes.

    This excludes array is a configuration property of jacoco plugin. Now, where to put this excludes array depends on whether you define your own tasks based on the jacoco plugin, or use a 'higher level plugin' that does this for you. For example using this plugin (you can see the plugin source to see where the excludes are actually applied):

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

    Connected tests

    If you're running android connected test coverage by setting testCoverageEnabled true in your buildType, unfortunately there is no idiomatic way to declare excludes, since the android gradle plugin doesn't provide such options, and the predefined jacoco report task has the excludes hardcoded. In this case, you have to script your own task with excludes.


    IntelliJ test runner

    If you're using the IntelliJ test runner, whether the coverage is done by IntelliJ or JaCoCo, you need to put the includes for a test configuration.

    1. Open the Edit Configurations window:

    1. Choose your test config and define includes (classes or whole packages). In this case I included the whole com.google.android.gms package, just as an example:

    To exclude dagger generated files, the quickest way is to put all the dagger dependencies in one root package, and include all the other packages in the test configuration.

提交回复
热议问题