Overview
A solid testing strategy is essential for building reliable Android applications. This guide covers testing approaches inspired by Google’s “Now in Android” sample, including unit tests, Hilt integration tests, and screenshot testing with Roborazzi.Testing Pyramid
Follow the testing pyramid for an effective test suite:- Unit Tests: Fast, isolated tests for business logic (ViewModels, Repositories, Use Cases)
- Integration Tests: Test component interactions (Room DAOs with database, Retrofit with MockWebServer)
- UI/Screenshot Tests: Verify UI correctness and prevent visual regressions (Compose UI)
Dependencies Setup
Add these testing dependencies to yourlibs.versions.toml:
build.gradle.kts:
Unit Testing
Unit tests are fast, focused tests that verify individual components in isolation.Testing ViewModels
Testing Use Cases
Integration Testing
Integration tests verify that multiple components work together correctly.Testing Room DAOs
Testing with MockWebServer
Hilt Testing
Hilt providesHiltAndroidRule and @HiltAndroidTest for dependency injection in tests.
Replacing Modules in Tests
Screenshot Testing with Roborazzi
Screenshot tests ensure your UI doesn’t regress visually. Roborazzi runs on the JVM (fast) without needing an emulator or device.Writing Screenshot Tests
Testing Individual Composables
Roborazzi Configuration Options
Roborazzi Configuration Options
Running Tests
Command Line
Android Studio
Test Best Practices
Writing Effective Unit Tests
Writing Effective Unit Tests
- Arrange-Act-Assert: Structure tests clearly with Given-When-Then or Arrange-Act-Assert
- One assertion per test: Focus each test on a single behavior
- Descriptive names: Use backticks for readable test names: `when user clicks button, navigate to details`
- Mock external dependencies: Use MockK or Mockito to isolate the unit under test
- Test edge cases: Null values, empty lists, error states, etc.
Integration Test Guidelines
Integration Test Guidelines
- Use real implementations: Test actual Room database, real Retrofit setup
- Clean state: Reset database/server state before each test
- Test interactions: Verify components work together correctly
- Reasonable scope: Don’t test the entire app - focus on specific integrations
Screenshot Test Tips
Screenshot Test Tips
- Test multiple states: Loading, success, error, empty states
- Test themes: Light and dark theme variations
- Test different configurations: Different screen sizes, font scales, locales
- Keep tests fast: Use JVM-based Roborazzi instead of instrumented tests
- Review diffs carefully: Check generated diff images when tests fail
- Version control baselines: Commit screenshot baselines to git
