Advanced testing cheat sheet

Revise Android advanced testing: test pyramid, fakes vs mocks, Robolectric, Hilt test setup, Roborazzi screenshot tests, Espresso, and flakiness fixes.

Key ideas

  1. Test pyramid: most tests are unit tests, fewer are integration tests, fewest are end-to-end; an inverted pyramid is a warning sign in code review.
  2. Prefer fakes over mocks for repositories (Google's guidance): a fake holds in-memory state, a mock returns what you stubbed.
  3. Local tests in src/test run on the JVM; instrumented tests in src/androidTest run on a device or emulator.
  4. Robolectric runs against targetSdk by default; use @Config(sdk = [...]) to test other API levels.
  5. Hilt tests need @HiltAndroidTest, HiltAndroidRule(this) as a @get:Rule, and hiltRule.inject() before using @Inject fields.
  6. Screenshot tests (Roborazzi, Paparazzi) run on the JVM; record and verify goldens on the same OS and renderer.
  7. Never use Thread.sleep in a test; wait for a real condition with an IdlingResource or composeRule.waitUntil.
  8. Enable Test Orchestrator with clearPackageData = "true" so instrumented tests do not share app data.
  9. Screenshot tests do not verify behaviour; pair them with ViewModel and UI tests.
  10. In MockK, use coEvery / coVerify for suspend functions inside runTest; fakes need neither.

APIs at a glance

API or termUse it for
@HiltAndroidTestAnnotation on a test class to enable Hilt dependency injection in that test.
HiltAndroidRuleJUnit rule that manages the Hilt test application lifecycle; call inject() in @Before.
@TestInstallInSwaps a Hilt module for the entire test source set via components and replaces.
@UninstallModules / @BindValueSwaps a Hilt module or binding for a single test class only.
@ConfigRobolectric annotation to set SDK level, screen qualifiers, or application = HiltTestApplication::class.
@GraphicsMode(GraphicsMode.Mode.NATIVE)Required on a Roborazzi test class so Robolectric renders real pixels instead of blank images.
captureRoboImage()Roborazzi call on a Compose onRoot() to write a screenshot golden.
mockk<T>() / coEvery / coVerifyMockK APIs to create a mock, stub behaviour, and verify calls on suspend functions.
CountingIdlingResourceReady-made IdlingResource that Espresso polls to know when async work is done.
composeRule.waitUntilWaits for a Boolean condition in Compose UI tests; the lambda must return Boolean, not assert.
ANDROIDX_TEST_ORCHESTRATORGradle testOptions.execution value that runs each instrumented test in a fresh process.
@PreviewTestCompose Preview Screenshot Testing annotation on previews in src/screenshotTest.

Snippets

Fake repository with Hilt test setup

// main source set
data class User(val id: String, val firstName: String, val lastName: String)
 
interface UserRepository {
    suspend fun getUser(id: String): User?
}
 
class GetDisplayNameUseCase @Inject constructor(private val repository: UserRepository) {
    suspend operator fun invoke(id: String): String =
        repository.getUser(id)?.let { "${it.firstName} ${it.lastName}" } ?: "Unknown"
}
 
// test source set
@Singleton
class FakeUserRepository @Inject constructor() : UserRepository {
    private val users = mutableMapOf<String, User>()
    fun seed(vararg seeded: User) = seeded.forEach { users[it.id] = it }
    override suspend fun getUser(id: String): User? = users[id]
}
 
@Module
@TestInstallIn(
    components = [SingletonComponent::class],
    replaces = [UserRepositoryModule::class], // the app's production @Module for UserRepository
)
abstract class FakeUserRepositoryModule {
    @Binds abstract fun bind(fake: FakeUserRepository): UserRepository
}
 
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
@Config(application = HiltTestApplication::class)
class GetDisplayNameUseCaseTest {
    @get:Rule val hiltRule = HiltAndroidRule(this)
    @Inject lateinit var fakeRepository: FakeUserRepository
    @Inject lateinit var getDisplayName: GetDisplayNameUseCase
 
    @Before fun setUp() { hiltRule.inject() }
 
    @Test
    fun joinsFirstAndLastName() = runTest {
        fakeRepository.seed(User("1", "Ada", "Lovelace"))
        assertEquals("Ada Lovelace", getDisplayName("1"))
    }
}

Roborazzi Compose screenshot test

@Composable
fun UserCard(name: String, online: Boolean) {
    Row(Modifier.padding(16.dp)) {
        Text(name)
        if (online) Text(" - online")
    }
}
 
@RunWith(AndroidJUnit4::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(qualifiers = "w360dp-h640dp-xhdpi")
class UserCardScreenshotTest {
    @get:Rule val composeRule = createComposeRule()
    @Test
    fun online() {
        composeRule.setContent {
            MaterialTheme { UserCard(name = "Ada Lovelace", online = true) }
        }
        composeRule.onRoot().captureRoboImage()
    }
}

Gradle Test Orchestrator setup

android {
    defaultConfig {
        testInstrumentationRunner = "com.example.app.HiltTestRunner" // your runner that uses HiltTestApplication
        testInstrumentationRunnerArguments["clearPackageData"] = "true"
    }
    testOptions {
        execution = "ANDROIDX_TEST_ORCHESTRATOR"
        animationsDisabled = true
    }
}
 
dependencies {
    androidTestUtil(libs.androidx.test.orchestrator) // androidx.test:orchestrator
}

Rules of thumb

  • Prefer fakes over mocks for your own repositories and data sources; reserve mocks for boundaries you cannot fake easily.
  • Never use Thread.sleep in a test; wait for a real condition with an IdlingResource or composeRule.waitUntil.
  • Never mock a data class or simple value type; pass the real instance to avoid obscuring intent.
  • Prefer local unit tests for pure logic; reserve Espresso and Compose test APIs for user journeys.
  • Never record and verify screenshot goldens on different OS or renderers; keep one tool per golden set.
  • Prefer @TestInstallIn for source-set-wide module swaps; use @BindValue when only one test class needs the override.

Gotchas

  • Mocking every repository. A mock returns only what you stubbed, so null handling, error mapping, and pagination bugs pass silently. Use a fake with in-memory state for your own data layer.
  • Forgetting HiltTestApplication in a Robolectric Hilt test. The test fails because the default application class is not a Hilt test application. Add @Config(application = HiltTestApplication::class) or the same setting in robolectric.properties.
  • Sharing one fake instance across tests. Mutable state leaks between tests and makes order matter. Create a new fake per test or reset it in @Before.
  • Putting an assertion inside waitUntil. The lambda must return a Boolean; an assertion throws instead of being retried. Check fetchSemanticsNodes().isNotEmpty() or use the waitUntil...Exists helpers.
  • Hitting a real API in an integration test. The test becomes slow, flaky, and breaks when the server changes. Replace the network layer with a fake or a local HTTP server such as MockWebServer.
  • Forgetting to unregister an IdlingResource. A resource left in IdlingRegistry can block or affect later tests in the same process. Register in @Before and unregister in @After.

Quick interview answers

When should you use a fake instead of a mock?

Use a fake for your own repositories and data sources because it holds in-memory state and lets you assert on outcomes. Use a mock when the interaction itself is the behaviour you care about, such as verifying that an analytics event was logged once.

What is the Android test pyramid and why is an inverted pyramid a problem?

The pyramid has the most tests at the unit level, fewer integration tests, and the fewest end-to-end tests. An inverted pyramid means too many slow, flaky UI tests and not enough fast unit tests, which slows the build and hides logic bugs.

How do you set up a Hilt test that runs under Robolectric?

Annotate the class with @HiltAndroidTest and @Config(application = HiltTestApplication::class), add HiltAndroidRule(this) as a @get:Rule, and call hiltRule.inject() in @Before. Use @TestInstallIn to swap production modules with fake modules for the whole source set.

How do you fix a flaky Espresso test caused by async work?

Register an IdlingResource (often CountingIdlingResource) with IdlingRegistry.getInstance().register() before the test acts, and unregister it in @After. In Compose, use composeRule.waitUntil with a Boolean condition instead of Thread.sleep.

What does Test Orchestrator do and when do you need it?

Test Orchestrator runs each instrumented test in a fresh process and, with clearPackageData = "true", clears app data between tests so order does not matter. Enable it via testOptions { execution = "ANDROIDX_TEST_ORCHESTRATOR" } plus the androidx.test:orchestrator dependency.

Why must screenshot tests be paired with behaviour tests?

A screenshot test only checks that the UI looks correct; a button that renders properly but calls the wrong function still passes. Add ViewModel and UI tests to verify that the visible outcome matches the intended behaviour.

Go deeper