How to have both Hilt and non-Hilt Android Instrumentation Tests in androidTest

238 Views Asked by At

TLDR; How to configure android instrumentation tests to run, so that we can have some hilt based tests and some which do not need hilt

I am able to create and run a simple espresso test with Jetpack compose but then I wanted to add hilttestrule and mock those dependencies. I followed this google hilt guide pretty accurately and was able to get hilt tests working but the initial createAndroidComposeRule won't work anymore with this error.

java.lang.IllegalStateException: The component was not created. Check that you have added the HiltAndroidRule.

The root cause is that I am modifying the testInstrumentationRunner to testInstrumentationRunner = "com.example.CustomTestRunner" and my customTestrunner which looks like this

class CustomTestRunner : AndroidJUnitRunner() {
    override fun newApplication(cl: ClassLoader?, name: String?, context: Context?): Application {
        return super.newApplication(cl, HiltTestApplication::class.java.name, context)
    }
}

is forcing a HiltTestApplication even for tests that do not need hilt configuration.

Some wacky ideas that didn't work

  1. Can I have multiple testInstrumentationRunners? If so, how can I configure them to be picking up different tests. Can I send some flags into defaultConfig from tests
  2. Or can I configure the CustomTestRunner to be only applicable when there is a specific Annotation on the tests? eg:
  override fun newApplication(cl: ClassLoader?, name: String?, context: Context?): Application {
        return when {
            runnerArgs.filters == androidx.filters.Large -> super.newApplication(cl, MyApp::class.java.name, context)
            else -> super.newApplication(cl, HiltTestApplication::class.java.name, context)
        }
    }

But runnerArgs is private and invisible to child classes and I can't access it.

0

There are 0 best solutions below