Test (Android Test Pyramid Compliant)
Create tests based on the official Android testing guidelines.
Test Pyramid
code
/ E2E \ Few: Complete user flows
/----------\
/ Integration \ Moderate: Multi-unit interactions
/----------------\
/ Unit Tests \ Many: Individual class verification
/____________________\
Test Types and Strategy
Unit Tests (Highest Priority)
Target: ViewModel, UseCase, Repository, Utility classes
Location: app/src/test/
Framework: JUnit 4/5 + kotlinx-coroutines-test
ViewModel Test Example
kotlin
class XxxViewModelTest {
@get:Rule
val mainDispatcherRule = MainDispatcherRule()
private lateinit var viewModel: XxxViewModel
private lateinit var fakeRepository: FakeXxxRepository
@Before
fun setup() {
fakeRepository = FakeXxxRepository()
viewModel = XxxViewModel(fakeRepository)
}
@Test
fun `initial state is correct`() = runTest {
val state = viewModel.uiState.value
assertEquals(XxxUiState(), state)
}
@Test
fun `action updates state correctly`() = runTest {
viewModel.onAction(XxxAction.DoSomething)
val state = viewModel.uiState.value
assertTrue(state.isLoading)
}
}
Testing Rules
- •Fake > Mock: Prefer Fake implementations over mocking libraries (Google's official recommendation)
- •1 test = 1 assertion: Each test verifies a single behavior
- •Naming: Use backtick syntax
`descriptive test name`() - •AAA Pattern: Arrange → Act → Assert
- •Coroutine testing: Use
runTest+TestDispatcher - •Edge cases: Test error paths and boundary conditions, not just the happy path
Integration Tests
Target: Repository + DataSource interaction, multi-UseCase coordination
Location: app/src/test/ or app/src/androidTest/
UI Tests (Compose)
Target: Screen display and interaction
Location: app/src/androidTest/
Framework: Compose Testing (createComposeRule)
kotlin
class XxxScreenTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun displaysCorrectContent() {
composeTestRule.setContent {
XxxScreen(state = XxxUiState(title = "Hello"))
}
composeTestRule.onNodeWithText("Hello").assertIsDisplayed()
}
}
Test Creation Procedure
Step 1: Analyze the Target
- •Read the class/feature to be tested
- •Identify dependencies
- •List behaviors to test
Step 2: Prepare Test Doubles
- •Repository → Create
FakeXxxRepository - •DataSource → Create
FakeXxxDataSource - •Dispatcher → Use
TestDispatcher - •Create
MainDispatcherRule(if not existing)
Step 3: Implement Tests
- •Happy path tests
- •Error path tests
- •Boundary value tests
- •State transition tests (for ViewModels)
Step 4: Run and Verify
bash
./gradlew test # Unit tests ./gradlew connectedAndroidTest # Instrumentation tests
Target
If $ARGUMENTS is specified, create tests for that class/feature. If not specified, identify areas with insufficient test coverage and add tests in priority order.