Test pyramid for Android
Why it matters
- An inverted pyramid (more end-to-end tests than unit tests) makes CI slow and flaky; developers start skipping tests and bugs reach production.
- Interviewers ask "how do you structure tests for a new feature?" and expect a pyramid answer that names real Android tools: JUnit, Robolectric, Hilt testing, Espresso and the Compose test APIs.
- Knowing which tests are local tests (JVM,
src/test) and which are instrumented tests (device or emulator,src/androidTest) decides how fast your feedback loop is. - Hilt testing with
@HiltAndroidTest,HiltAndroidRule,@UninstallModules,@TestInstallInand@BindValueis the standard way to swap bindings in a Hilt codebase.
The simple explanation
- A house: many small bricks (unit tests) at the base, fewer beams (integration tests) in the middle, a small roof (end-to-end tests) on top.
- Bricks are cheap and quick to check; the roof is expensive to inspect.
- A house with a huge roof and few bricks is slow to build and leaks (flaky tests).
What is the Android test pyramid? It is a way to balance tests by size: many fast, focused unit tests at the base, fewer integration tests that check several parts together, and a small number of slow end-to-end tests that run the whole app on a device. Small tests give fast, precise feedback; big tests give confidence that the parts work together. Android's testing guide calls these small, medium and big tests.
Android also splits tests by where they run:
- Local tests live in
src/testand run on your machine's JVM. Plain Kotlin logic needs nothing else. Code that touches Android classes (Context, resources, Room, even Compose UI) can run here with Robolectric, which provides a simulated Android framework on the JVM. - Instrumented tests live in
src/androidTestand run on a device or emulator. They are slower but use the real framework and real rendering.
| Level | Typical tools | Runs on | Covers |
|---|---|---|---|
| Unit (small) | JUnit 4, runTest, fakes | Local JVM | ViewModels, use cases, mappers, pure logic |
| Integration (medium) | Robolectric, Hilt testing, in-memory Room | Local JVM or device | Repository + DAO, DI graph, one screen with fakes |
| End-to-end (big) | Espresso, Compose test APIs, UI Automator | Device or emulator | Full user journeys across screens |
Hilt testing uses @HiltAndroidTest plus a HiltAndroidRule to build a test DI graph, and hiltRule.inject() to fill @Inject fields. To swap a production binding: @TestInstallIn replaces a module for every test in the source set; @UninstallModules plus a nested module, or @BindValue, replaces it for one test class. Under Robolectric, set the application with @Config(application = HiltTestApplication::class); on a device, use a custom runner that creates HiltTestApplication.
Google's testing guidance prefers fakes for repositories and data sources: a fake is a working, simplified implementation with in-memory state, so tests check real outcomes instead of a list of calls.
At the top, Espresso drives View-based UI inside your app, the Compose test APIs (createComposeRule, createAndroidComposeRule, onNodeWithText) drive Compose UI, and UI Automator reaches outside your app (system dialogs, other apps). Gradle Managed Devices let Gradle create and start emulators from your build file, so CI and laptops run instrumented tests on the same device definitions.
The next lessons cover fakes vs mocks, screenshot testing, and end-to-end flakiness in depth.
Notes
- Pyramid shape: most tests are unit tests, fewer are integration tests, fewest are end-to-end. An inverted pyramid is a warning sign in code review.
- Local tests (
src/test) run on the JVM; instrumented tests (src/androidTest) run on a device or emulator. - Plain Kotlin logic needs only JUnit. Use Robolectric only when the code touches Android classes; it adds start-up cost.
- Robolectric runs tests against your
targetSdkby default (capped at the newest SDK it supports). Use@Config(sdk = [...])when you want to test other API levels. - Hilt test setup:
@HiltAndroidTeston the class,HiltAndroidRule(this)as a@get:Rule, andhiltRule.inject()before using@Injectfields. @TestInstallIn(components = [...], replaces = [ProdModule::class])swaps a module for the whole test source set;@UninstallModulesor@BindValueswap it for one test class.- Prefer fakes over mocks for repositories (Google's guidance). A fake holds state; a mock returns what you stubbed.
- End-to-end tools: Espresso for in-app Views, Compose test APIs for Compose, UI Automator for cross-app and system UI.
- Common flakiness sources: animations, real network, wall-clock time, shared state between tests, async work the framework cannot see.
- Gradle Managed Devices define emulators in Gradle, so the same device profile runs locally and in CI.
Code example
This shows a Hilt integration test that runs on the JVM with Robolectric. A @TestInstallIn module swaps the production repository for a fake in every test of the source set, and the test checks a real use case against that fake.
// main: the production code
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)?.name?.takeIf { it.isNotBlank() } ?: "Guest"
}
// test: a fake with in-memory state, one instance per test graph
@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]
}
// test: replaces the production DataModule in every test of this source set
@Module
@TestInstallIn(components = [SingletonComponent::class], replaces = [DataModule::class])
abstract class FakeDataModule {
@Binds
abstract fun bindUserRepository(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 knownUserShowsName() = runTest {
fakeRepository.seed(User(id = "1", name = "Ada"))
assertEquals("Ada", getDisplayName("1"))
}
@Test
fun unknownUserShowsGuest() = runTest {
assertEquals("Guest", getDisplayName("missing"))
}
}FakeUserRepositoryis@Singleton, so the instance injected into the test is the same one the use case receives.@TestInstallInlives in the test source set and replacesDataModulefor every Hilt test there; no per-class setup is needed.@Config(application = HiltTestApplication::class)tells Robolectric to use Hilt's test application. Each test gets a fresh Hilt graph, so the fake starts empty.- Without Hilt, the same use case can be tested in a plain JUnit test by passing
FakeUserRepository()to its constructor. That is faster and is the right choice when you are not testing the DI wiring itself.
Run the idea in plain Kotlin
data class TestLevel(
val name: String,
val count: Int,
val speed: String
)
fun main() {
val pyramid = listOf(
TestLevel("Unit (local JVM)", 800, "ms"),
TestLevel("Integration (Robolectric, Hilt)", 120, "s"),
TestLevel("E2E (device)", 15, "min")
)
val total = pyramid.sumOf { it.count }
println("Total tests: " + total)
println()
for (level in pyramid) {
val pct = level.count * 100 / total
val bar = "#".repeat(pct / 2)
println(level.name + " " + level.count + " tests (" + pct + "%) " + bar)
}
println()
val unitPct = pyramid[0].count * 100 / total
val e2ePct = pyramid[2].count * 100 / total
if (unitPct > e2ePct * 10) {
println("Pyramid shape: OK (unit >> e2e)")
} else {
println("Pyramid shape: INVERTED - too many E2E tests")
}
}Expected output:
Total tests: 935
Unit (local JVM) 800 tests (85%) ##########################################
Integration (Robolectric, Hilt) 120 tests (12%) ######
E2E (device) 15 tests (1%)
Pyramid shape: OK (unit >> e2e)
In production
- CI ran hundreds of Espresso tests on emulators; each full run took a long time.
- Flaky failures grew as more end-to-end tests were added, and developers started marking tests with
@Ignore. - Business logic (date formatting, validation) was only tested through the UI, so a one-line logic bug needed a full device run to catch.
- Moved business logic into use cases and ViewModels with no Android dependencies.
- Covered that logic with local JUnit tests using fakes; kept only critical user journeys as end-to-end tests.
- CI got much faster and the team stopped skipping tests.
- Robolectric Room tests passed when run one at a time but failed intermittently in the full suite.
- A test helper kept one in-memory database in a
companion object, so rows written by one test were visible to the next. - Test order changed between runs, so the failures looked random.
- Each test builds its own database with
Room.inMemoryDatabaseBuilder(...)in@Beforeand closes it in@After. - Removed the shared
companion objectstate from the helper. - Added a check in review: no mutable state in test companion objects or top-level properties.
Common mistakes
- Mocking every repository. A mock returns whatever you stubbed, so it can hide bugs in null handling or mapping. Use a fake with in-memory state for your own repositories; keep mocks for boundaries you cannot fake easily.
- Writing an Espresso test for pure logic. A date-formatting check through the UI is slow, flaky and breaks on unrelated UI changes. Test logic in a local unit test; keep end-to-end tests for user journeys.
- Using Robolectric for plain Kotlin code. Robolectric adds start-up time to every test class. If the code never touches Android classes, a plain JUnit test is enough.
- Forgetting HiltTestApplication. A Robolectric Hilt test without
@Config(application = HiltTestApplication::class)(or the same setting inrobolectric.properties) fails because the app class is not a Hilt test application. - Hitting a real API in an integration test. The test becomes slow and flaky and breaks when the server changes. Replace the network layer with a fake, or use a local HTTP server such as MockWebServer.
- Shared mutable state across tests. A singleton or
companion objectthat holds data between tests makes order matter. Create fresh instances per test or reset state in@Before.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“Describe the Android test pyramid and how you would apply it to a new feature.”
“When would you choose Robolectric over a real instrumented test?”
“How do you set up a Hilt test that replaces a repository with a fake?”
“A CI end-to-end test is flaky. Walk me through your diagnosis.”
Quiz
Which Hilt annotation replaces a production module with a test module for every test in the test source set?
What does Robolectric do?
Per Google's testing guidance, which test double is preferred for a repository in a unit test?
Where do Android instrumented tests live and run?
0 of 4 answered
Mini task
Add a Hilt integration test with a fake repository (15 min)
-
Create the fake. In
src/test, add a@SingletonFakeUserRepository @Inject constructor()that implementsUserRepositorywith amutableMapOf<String, User>()and aseed()function. -
Replace the module. In
src/test, add a@Modulewith@TestInstallIn(components = [SingletonComponent::class], replaces = [DataModule::class])that@Bindsthe fake toUserRepository. -
Write the test class. Add
@HiltAndroidTest,@RunWith(AndroidJUnit4::class)and@Config(application = HiltTestApplication::class). Add aHiltAndroidRuleas a@get:Ruleand callhiltRule.inject()in@Before. -
Test both paths. Inject the fake and a use case. In one test, seed a user and assert the use case returns its name. In another, do not seed and assert the fallback value.
-
Run the tests. Execute
./gradlew :app:testDebugUnitTest --tests "*GetDisplayNameUseCaseTest".
Done condition: Two passing local tests that use the real Hilt graph with a fake repository, with no network and no emulator.