Best Practices
Keep your Espresso tests reliable and maintainable.
Best practices checklist
text
✅ Use ActivityScenarioRule (not ActivityTestRule — deprecated)
✅ Register IdlingResources for all async operations (network, DB, animations)
✅ Disable animations in developer settings (or via test setup)
✅ Use R.id locators primarily; combine with withText() for specificity
✅ Keep tests independent — each test sets up its own state
✅ Use @Rule + ActivityScenario for flexible activity launching
✅ Mock external dependencies with Hilt or Dagger in tests
✅ Run on an emulator with API 21+ for consistency
✅ Use allOf() to narrow down matching when IDs are duplicated
✅ Add closeSoftKeyboard() after typeText() to prevent keyboard overlap issuesDisable animations (test setup)
kotlin
// In your test runner or @BeforeClass:
// OR add this to your gradle:
android {
testOptions {
animationsDisabled = true
}
}