Instrumentation testing

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 Android instrumentation tests, the application can be set using a custom test runner that extends AndroidJUnitRunner. To set the application using the runner, just override the newApplication method and pass in the application class name. For Hilt tests, the application must either be HiltTestApplication or one of Hilt’s custom test applications.

Java
Kotlin
package my.pkg;

public final class MyTestRunner extends AndroidJUnitRunner {
  @Override
  public Application newApplication(
      ClassLoader cl, String appName, Context context) {
    return super.newApplication(
        cl, HiltTestApplication.class.getName(), context);
  }
}
package my.pkg

class MyTestRunner extends AndroidJUnitRunner {
  override fun newApplication(
      cl: ClassLoader,
      appName: String,
      context: Context) : Application {
    return super.newApplication(
        cl, HiltTestApplication::class.java.getName(), context)
  }
}

In addition, the testInstrumentationRunner must be configured in the build.gradle file for the given Gradle module:

android {
  defaultConfig {
      testInstrumentationRunner "my.pkg.MyTestRunner"
  }
}