Is there any option to exclude Dagger2 classes from test coverage report in Android Studio
The easiest way to exclude code from code coverage analysis is to use ExcludeFromCodeCoverage attribute. This attribute tells tooling that class or some of its members are not planned to be covered with tests. EditFormModel class shown above can be left out from code coverage by simply adding the attribute.
Starting from JaCoCo 0.8. 2, we can exclude classes and methods by annotating them with a custom annotation with the following properties: The name of the annotation should include Generated. The retention policy of annotation should be runtime or class.
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' ] }
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With