Robolectric testing

Warning: See here for limitations when running Robolectric tests via Android Studio when using the Hilt Gradle plugin.

Setting the test application

Hilt’s testing APIs are built to be agnostic of the particular testing environment; however, the instructions for setting up the application class in your test will depend on whether you are using Robolectric or Android instrumentation tests.

For Robolectric tests, the application can be set either locally using @Config or globally using robolectric.properties. For Hilt tests, the application must either be HiltTestApplication or one of Hilt’s custom test applications.

Note: This setup is not particular to Hilt. See the official Robolectric documentation for more details.

Using @Config

The Hilt application class can be set locally using @Config. To set the application, just annotate the test (or test method) with @Config and set the value of the annotation to the desired application class.

Java
Kotlin
@HiltAndroidTest
@Config(application = HiltTestApplication.class)
public class FooTest {...}
@HiltAndroidTest
@Config(application = HiltTestApplication::class)
class FooTest {...}

Using robolectric.properties

The Hilt application class can be set globally using the robolectric.properties file. To set the application, just create the robolectric.properties file in the appropriate resources package, and set the Hilt test application class.

application=dagger.hilt.android.testing.HiltTestApplication

This approach can be useful when a test needs to run in both Robolectric and Android instrumentation environments, since the @Config annotation cannot be used with Android instrumentation tests.