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 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 offical 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.

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


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

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.