11-testing.md
.codex/skills/compose-kotlin-agent-skills/references/11-testing.md
1# Testing — ViewModels, Compose UI, Hilt, E2E23## Contents45- ViewModel testing with Turbine6- TestDispatcher setup7- Compose UI testing8- Hilt testing — TestInstallIn, fakes9- What to test, what to skip1011## ViewModel Testing with Turbine1213Turbine = library for testing Kotlin Flows. Essential for testing ViewModels.1415```toml16[dependencies]17turbine = { module = "app.cash.turbine:turbine", version = "1.2.0" }18kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }19```2021### Basic ViewModel Test2223```kotlin24class AuthViewModelTest {25 @get:Rule26 val mainDispatcherRule = MainDispatcherRule()2728 private lateinit var fakeRepo: FakeAuthRepository29 private lateinit var viewModel: AuthViewModel3031 @Before32 fun setup() {33 fakeRepo = FakeAuthRepository()34 viewModel = AuthViewModel(fakeRepo)35 }3637 @Test38 fun `initial state is loading`() = runTest {39 viewModel.uiState.test {40 val initial = awaitItem()41 assertTrue(initial.isLoading)42 }43 }4445 @Test46 fun `accounts loaded after init`() = runTest {47 val accounts = listOf(48 AuthAccount("1", "Google", "test@gmail.com", "secret", "🔍")49 )50 fakeRepo.emitAccounts(accounts)5152 viewModel.uiState.test {53 skipItems(1) // skip loading state54 val loaded = awaitItem()55 assertFalse(loaded.isLoading)56 assertEquals(1, loaded.accounts.size)57 assertEquals("Google", loaded.accounts.first().serviceName)58 }59 }6061 @Test62 fun `search filters accounts`() = runTest {63 fakeRepo.emitAccounts(listOf(64 AuthAccount("1", "Google", "test@gmail.com", "s1", "🔍"),65 AuthAccount("2", "GitHub", "user", "s2", "🐙")66 ))6768 viewModel.uiState.test {69 skipItems(1) // loading70 awaitItem() // all accounts7172 viewModel.onSearchChanged("git")73 val filtered = awaitItem()74 assertEquals(1, filtered.accounts.size)75 assertEquals("GitHub", filtered.accounts.first().serviceName)76 }77 }7879 @Test80 fun `delete account removes from list`() = runTest {81 fakeRepo.emitAccounts(listOf(82 AuthAccount("1", "Google", "test", "s1", "🔍")83 ))8485 viewModel.uiState.test {86 skipItems(1)87 awaitItem() // 1 account8889 viewModel.onDeleteAccount("1")90 val afterDelete = awaitItem()91 assertTrue(afterDelete.accounts.isEmpty())92 }93 }94}95```9697### FakeRepository9899```kotlin100class FakeAuthRepository : AuthRepository {101 private val accounts = MutableStateFlow<List<AuthAccount>>(emptyList())102103 fun emitAccounts(list: List<AuthAccount>) {104 accounts.value = list105 }106107 override fun getAllAccounts(): Flow<List<AuthAccount>> = accounts108109 override suspend fun insertAccount(account: AuthAccount) {110 accounts.update { it + account }111 }112113 override suspend fun deleteAccountById(id: String) {114 accounts.update { list -> list.filter { it.id != id } }115 }116117 override suspend fun getAccountById(id: String): AuthAccount? =118 accounts.value.find { it.id == id }119120 override fun searchAccounts(query: String): Flow<List<AuthAccount>> =121 accounts.map { list ->122 list.filter { it.serviceName.contains(query, ignoreCase = true) }123 }124}125```126127**Fakes over mocks.** Fakes implement the interface with in-memory data. Mocks (Mockito/MockK) verify method calls but don't test behavior. Fakes catch bugs mocks miss.128129## TestDispatcher Setup130131```kotlin132class MainDispatcherRule(133 private val dispatcher: TestDispatcher = UnconfinedTestDispatcher()134) : TestWatcher() {135136 override fun starting(description: Description) {137 Dispatchers.setMain(dispatcher)138 }139140 override fun finished(description: Description) {141 Dispatchers.resetMain()142 }143}144```145146**Why:** ViewModels use `viewModelScope` which dispatches on `Dispatchers.Main`. Tests run on JVM — no Main dispatcher. `MainDispatcherRule` replaces Main with test dispatcher.147148`UnconfinedTestDispatcher` — executes eagerly (no delay). Use for most ViewModel tests.149`StandardTestDispatcher` — requires `advanceUntilIdle()`. Use when testing timing-sensitive code.150151## Compose UI Testing152153```kotlin154class AccountsScreenTest {155 @get:Rule156 val composeRule = createComposeRule()157158 @Test159 fun `displays account list`() {160 val accounts = listOf(161 AuthAccount("1", "Google", "test@gmail.com", "s1", "🔍"),162 AuthAccount("2", "GitHub", "user", "s2", "🐙")163 )164165 composeRule.setContent {166 MaterialTheme {167 AccountsContent(168 accounts = accounts,169 searchQuery = "",170 onSearchChanged = {},171 onDelete = {},172 onAdd = {}173 )174 }175 }176177 composeRule.onNodeWithText("Google").assertIsDisplayed()178 composeRule.onNodeWithText("GitHub").assertIsDisplayed()179 }180181 @Test182 fun `search bar filters content`() {183 var capturedQuery = ""184 composeRule.setContent {185 AccountsContent(186 accounts = emptyList(),187 searchQuery = "",188 onSearchChanged = { capturedQuery = it },189 onDelete = {},190 onAdd = {}191 )192 }193194 composeRule.onNodeWithTag("search_bar").performTextInput("Google")195 assertEquals("Google", capturedQuery)196 }197198 @Test199 fun `delete button triggers callback`() {200 var deletedId = ""201 composeRule.setContent {202 AccountCard(203 account = AuthAccount("1", "Google", "test", "s1", "🔍"),204 onDelete = { deletedId = it }205 )206 }207208 composeRule.onNodeWithContentDescription("Delete account")209 .performClick()210 assertEquals("1", deletedId)211 }212}213```214215### Test Tags216217```kotlin218// In production code219TextField(220 modifier = Modifier.testTag("search_bar"),221 value = query,222 onValueChange = onQueryChange223)224225// In test226composeRule.onNodeWithTag("search_bar").performTextInput("query")227```228229### Testing Content Composable, Not Screen230231```kotlin232// DON'T test the screen with ViewModel — that's integration testing233// DO test the stateless content composable234@Composable235fun AccountsContent( // ← test this236 accounts: List<AuthAccount>,237 searchQuery: String,238 onSearchChanged: (String) -> Unit,239 onDelete: (String) -> Unit,240 onAdd: (AuthAccount) -> Unit241)242```243244Stateless content composables are pure functions of their params. Easy to test in isolation.245246## Hilt Testing247248### TestInstallIn — Replace Module249250```kotlin251@Module252@TestInstallIn(253 components = [SingletonComponent::class],254 replaces = [RepositoryModule::class]255)256abstract class TestRepositoryModule {257 @Binds258 @Singleton259 abstract fun bindRepo(impl: FakeAuthRepository): AuthRepository260}261262@HiltAndroidTest263@RunWith(AndroidJUnit4::class)264class AccountsIntegrationTest {265 @get:Rule(order = 0)266 val hiltRule = HiltAndroidRule(this)267268 @get:Rule(order = 1)269 val composeRule = createAndroidComposeRule<MainActivity>()270271 @Inject272 lateinit var repo: AuthRepository273274 @Before275 fun setup() {276 hiltRule.inject()277 }278279 @Test280 fun fullAccountFlow() {281 // Test with real DI graph but fake repository282 composeRule.onNodeWithText("Add Account").performClick()283 // ...284 }285}286```287288## What to Test vs Skip289290### Always Test291| What | Why | Tool |292|------|-----|------|293| ViewModel state logic | Core business logic | Turbine + runTest |294| Flow transformations | combine, map, filter correctness | Turbine |295| Error handling paths | Failure states must work | Fake that throws |296| Repository mapping | DTO/Entity → Domain correctness | Unit test |297298### Test If Time Allows299| What | Why | Tool |300|------|-----|------|301| Compose UI rendering | Catch layout regressions | composeRule |302| Navigation flows | Correct destination on actions | TestNavHostController |303| Accessibility | TalkBack reads correctly | semantics assertions |304305### Skip306| What | Why |307|------|-----|308| Room DAO queries (simple) | Room's annotation processor generates correct SQL |309| Hilt module wiring | Compile-time verified |310| UI pixel perfection | Screenshot tests are brittle, use design review instead |311| External API calls | Mock the repository, not the HTTP client |312313## Test File Organization314315```316src/test/ # Unit tests (JVM, fast)317├── viewmodel/318│ ├── AuthViewModelTest.kt319│ └── WorkoutViewModelTest.kt320├── repository/321│ └── AuthRepositoryTest.kt322└── fakes/323 ├── FakeAuthRepository.kt324 └── FakeWorkoutRepository.kt325326src/androidTest/ # Instrumented tests (device/emulator)327├── ui/328│ ├── AccountsScreenTest.kt329│ └── WorkoutFlowTest.kt330└── navigation/331 └── AppNavigationTest.kt332```333334## Anti-Patterns335336- **Mocking everything with MockK** → tests pass but don't verify behavior. Fakes > mocks337- **Testing ViewModel with real repository** → slow, flaky, tests two things. Use fake338- **`Thread.sleep()` in tests** → flaky. Use `advanceUntilIdle()` or Turbine's `awaitItem()`339- **Testing private ViewModel functions** → test through public state. If `_calculateScore()` is correct, `state.score` reflects it340- **One giant test class** → split by feature. `AuthViewModelTest`, `WorkoutViewModelTest`341- **No test dispatcher rule** → tests hang or fail on `Dispatchers.Main`. Always include `MainDispatcherRule`342