Local vs instrumented tests

Testing Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

A team's 400 Espresso tests take 50 minutes in CI and are flaky. Most check ViewModel logic through the UI. Best move?

Options
Hint 1 of 1

Does checking ViewModel logic need a device?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Move logic checks to local ViewModel tests with fakes and keep a few UI tests for key journeys

Correct. Logic tests run in seconds on the JVM; UI tests cover only what needs a device.

Why not the others?
  • B Run the Espresso tests on more emulators. Faster, but still slow and flaky.
  • C Delete the tests. Loses coverage.
  • D Add Thread.sleep to stabilise them. Makes them slower and still flaky.

30-second answer

Local tests run on the JVM on your machine in src/test: fast, cheap and ideal for ViewModels, use cases, repositories with fakes, and mappers. Instrumented tests run on a device or emulator in src/androidTest: slower, but they test real Android behaviour like Room, UI and navigation. Write many local tests, fewer integration tests, and a small number of end-to-end UI tests.

Practise saying it · 30 s. No recording, just a timer

Explain local vs instrumented tests.

Say your answer out loud, then check which of these points you covered:

  • Local: JVM, fast, logic
  • Instrumented: device, real Android
  • Many local, few UI tests
  • Keep logic out of Android classes

Deep dive

Robolectric runs some Android framework code on the JVM, useful for Compose UI tests without a device.

Gradle Managed Devices run instrumented tests on emulators defined in the build.

Test behaviour through public APIs, not private implementation details.

Keep business logic out of Android classes so it can be tested locally.

Common mistakes

  • Testing everything through the UI.
  • Putting logic in Activities, which forces instrumented tests.
  • Mocking every class instead of using small fakes.

Senior take & follow-ups

Explain trade-offs: speed, fidelity and cost. Then where each layer of the app is tested.

Follow-up questions

Think of your answer first, then open the hint.

  1. What does Robolectric give you?

    Show hint

    A simulated Android framework on the JVM.

  2. What are Gradle Managed Devices?

    Show hint

    Emulators configured in Gradle that CI can start for tests.

Similar on iOS: Writing good unit tests with XCTest iOS runs unit tests in the simulator; Android's local tests run on the plain JVM.

Suggest a fix if something here is wrong or out of date.