Advanced testing cheat sheet
Key ideas
- 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.
- Prefer fakes over mocks for repositories (Google's guidance): a fake holds in-memory state, a mock returns what you stubbed.
- Local tests in
src/testrun on the JVM; instrumented tests insrc/androidTestrun on a device or emulator. - Robolectric runs against
targetSdkby default; use@Config(sdk = [...])to test other API levels. - Hilt tests need
@HiltAndroidTest,HiltAndroidRule(this)as a@get:Rule, andhiltRule.inject()before using@Injectfields. - Screenshot tests (Roborazzi, Paparazzi) run on the JVM; record and verify goldens on the same OS and renderer.
- Never use
Thread.sleepin a test; wait for a real condition with anIdlingResourceorcomposeRule.waitUntil. - Enable Test Orchestrator with
clearPackageData = "true"so instrumented tests do not share app data. - Screenshot tests do not verify behaviour; pair them with ViewModel and UI tests.
- In MockK, use
coEvery/coVerifyforsuspendfunctions insiderunTest; fakes need neither.
APIs at a glance
| API or term | Use it for |
|---|---|
@HiltAndroidTest | Annotation on a test class to enable Hilt dependency injection in that test. |
HiltAndroidRule | JUnit rule that manages the Hilt test application lifecycle; call inject() in @Before. |
@TestInstallIn | Swaps a Hilt module for the entire test source set via components and replaces. |
@UninstallModules / @BindValue | Swaps a Hilt module or binding for a single test class only. |
@Config | Robolectric 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 / coVerify | MockK APIs to create a mock, stub behaviour, and verify calls on suspend functions. |
CountingIdlingResource | Ready-made IdlingResource that Espresso polls to know when async work is done. |
composeRule.waitUntil | Waits for a Boolean condition in Compose UI tests; the lambda must return Boolean, not assert. |
ANDROIDX_TEST_ORCHESTRATOR | Gradle testOptions.execution value that runs each instrumented test in a fresh process. |
@PreviewTest | Compose 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.sleepin a test; wait for a real condition with anIdlingResourceorcomposeRule.waitUntil. - Never mock a
data classor 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
@TestInstallInfor source-set-wide module swaps; use@BindValuewhen 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 inrobolectric.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. CheckfetchSemanticsNodes().isNotEmpty()or use thewaitUntil...Existshelpers. - 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
IdlingRegistrycan block or affect later tests in the same process. Register in@Beforeand 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.