Article
Dagger Hilt: Testing injected Android components with code coverage
November 17, 2020

Dagger Hilt is Google’s new opinionated add-on for setting up Dagger 2 for Android. Through its tie-ins with androidx
and preconfigured components, it should be able to meet the common dependency injection demands of most apps.
Google also lays out a testing philosophy that Hilt can help realize, using the real Dagger graph in tests. The goal of this article is to make that philosophy a reality, by providing all of the build script pieces and an inheritance trick needed to set up testing an Android project with code coverage using Hilt, Robolectric, Espresso and JaCoCo.
- 1: Configure JaCoCo
- 2: Setup Robolectric and Espresso
- 3a: Configure Hilt with the Gradle plugin
- 3b: Configure Hilt without the Gradle plugin
This article won’t explain how to write tests for Robolectric and Espresso, or how to use Hilt’s testing utilities, so refer to the documentation for those projects for examples.
Step 1: Configure JaCoCo
The necessary JaCoCo configuration looks basically the same as a normal Android JaCoCo setup. Since it’s not a trivial task to set up, here is a sample build configuration that creates separate test reports for each application variant while also allowing for exclusions: