games-minesweeper: add tests for stats, game flows, home and dialogs
- Commit
d63b0f39cdb142c06fe6fb43bf0ad7ba16be1569- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 11:20 UTC (29 days ago)
- Parents
2c37f0b
Pass 3 for :games:minesweeper (was 54.9% merged): - MinesweeperStatsRepository per-variant records and per-size aggregation, best-time/streak semantics, corrupt-record behaviour; MinesweeperAchievementsManager back-fill from stats (first win / large / expert / speed); AppBackupAgent lists; Route and GameConfig serialization. - ViewModel end-of-game flows driven from the laid field: winning by revealing every safe cell (stats recorded), losing on a mine (exploded cell, streak reset), chording with matching and mismatched flag counts (target cell found by re-dealing, so no random-layout flake), flag/dig mode interplay for taps and long presses, give-up accounting before and after the first dig, restart/timer guards. - Compose under Robolectric: HomeScreen new-game dialog flow, Continue, dismiss, and stat cards with recorded results; GameConfigDialog seeded initial config, live mine-count text as size/difficulty change, start and dismiss for several combinations; all size/difficulty display names; GameScreen dealing, won/lost board overlays (time shown only on a win), tap-mode toggle, and the new-field / give-up confirmation dialogs; Navigation and MainActivity. 60 unit tests pass (31 existing + 29 new). Merged INSTRUCTION coverage: 54.9% -> 95.3% (6130/6430 instructions). Untestable remainder: GameScreen timer loop body beyond the first composition, MainActivity beyond onCreate. No production code changes. (cherry picked from commit b75981b6f759941c4152a9590092955a298aebcf)
Diff
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/data/MinesweeperRepositoriesTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/data/MinesweeperRepositoriesTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/data/MinesweeperRepositoriesTest.ktnew file mode 100644index 0000000000..943ced46da--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/data/MinesweeperRepositoriesTest.kt@@ -0,0 +1,126 @@+package com.vayunmathur.games.minesweeper.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.minesweeper.Route+import com.vayunmathur.games.minesweeper.platform.AppBackupAgent+import com.vayunmathur.games.minesweeper.platform.MinesweeperAchievementsManager+import kotlinx.serialization.json.Json+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Stats persistence/aggregation, achievements back-fill, backup, routes. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MinesweeperRepositoriesTest {+ private val ctx get() = ApplicationProvider.getApplicationContext<Context>()++ @BeforeTest fun clearPrefs() {+ ctx.getSharedPreferences("minesweeper_stats", Context.MODE_PRIVATE).edit().clear().commit()+ }++ @Test fun statsPerVariantAndSizeAggregation() {+ val repo = MinesweeperStatsRepository(ctx)+ assertEquals(GameStats(), repo.getStats(BoardSize.SMALL, Difficulty.EASY))+ assertEquals(GameStats(), repo.getSizeStats(BoardSize.SMALL))+ assertEquals(0, repo.getTotalGamesWon())+ assertEquals(0, repo.getBestWinStreak())++ repo.recordGamePlayed(BoardSize.SMALL, Difficulty.EASY)+ repo.recordGamePlayed(BoardSize.SMALL, Difficulty.EASY)+ repo.recordGamePlayed(BoardSize.SMALL, Difficulty.HARD)+ repo.recordGameWon(BoardSize.SMALL, Difficulty.EASY, 300)+ repo.recordGameWon(BoardSize.SMALL, Difficulty.EASY, 90)+ repo.recordGameWon(BoardSize.SMALL, Difficulty.HARD, 45)++ val easy = repo.getStats(BoardSize.SMALL, Difficulty.EASY)+ assertEquals(2, easy.gamesPlayed)+ assertEquals(2, easy.gamesWon)+ assertEquals(2, easy.bestWinStreak)+ assertEquals(90, easy.bestTimeSeconds)++ val size = repo.getSizeStats(BoardSize.SMALL)+ assertEquals(3, size.gamesPlayed)+ assertEquals(3, size.gamesWon)+ assertEquals(2, size.currentWinStreak)+ assertEquals(45, size.bestTimeSeconds)+ assertEquals(GameStats(), repo.getSizeStats(BoardSize.LARGE))+ assertEquals(3, repo.getTotalGamesWon())+ assertEquals(2, repo.getBestWinStreak())++ repo.recordGameLost(BoardSize.SMALL, Difficulty.EASY)+ assertEquals(0, repo.getStats(BoardSize.SMALL, Difficulty.EASY).currentWinStreak)+ assertEquals(2, repo.getStats(BoardSize.SMALL, Difficulty.EASY).bestWinStreak)+ // Records survive a fresh repository over the same prefs.+ assertEquals(3, MinesweeperStatsRepository(ctx).getTotalGamesWon())+ }++ @Test fun bestTimeOnlyImprovesAndStreakAcrossSizes() {+ val repo = MinesweeperStatsRepository(ctx)+ repo.recordGameWon(BoardSize.MEDIUM, Difficulty.MEDIUM, 200)+ repo.recordGameWon(BoardSize.MEDIUM, Difficulty.MEDIUM, 250)+ assertEquals(200, repo.getStats(BoardSize.MEDIUM, Difficulty.MEDIUM).bestTimeSeconds)+ repo.recordGameWon(BoardSize.LARGE, Difficulty.EXPERT, 30)+ repo.recordGameWon(BoardSize.LARGE, Difficulty.EXPERT, 20)+ assertEquals(2, repo.getBestWinStreak())+ assertEquals(4, repo.getTotalGamesWon())+ }++ @Test fun corruptedRecordThrowsOnRead() {+ ctx.getSharedPreferences("minesweeper_stats", Context.MODE_PRIVATE)+ .edit().putString("stats_SMALL__EASY", "{oops").commit()+ val repo = MinesweeperStatsRepository(ctx)+ assertFailsWith<kotlinx.serialization.SerializationException> {+ repo.getStats(BoardSize.SMALL, Difficulty.EASY)+ }+ }++ @Test fun gameStatsDefaults() {+ val s = GameStats()+ assertEquals(Int.MAX_VALUE, s.bestTimeSeconds)+ assertEquals(GameStats(gamesWon = 2), s.copy(gamesWon = 2))+ }++ @Test fun achievementsBackfillFromStats() {+ val repo = MinesweeperStatsRepository(ctx)+ // No wins: check runs cleanly.+ val json = ctx.assets.open("achievements.json").bufferedReader().readText()+ MinesweeperAchievementsManager(ctx, json, repo).checkExistingAchievements()+ // Wins that satisfy first_win, win_large, win_expert and speed_win.+ repo.recordGameWon(BoardSize.LARGE, Difficulty.EXPERT, 30)+ repo.recordGameWon(BoardSize.SMALL, Difficulty.EASY, 500)+ val manager = MinesweeperAchievementsManager(ctx, json, repo)+ manager.checkExistingAchievements()+ manager.dismissNotification()+ // A slow large win still back-fills size/expert but the check itself+ // must simply run (unlock delivery is DataStore-async in the library).+ assertTrue(repo.getTotalGamesWon() == 2)+ }++ @Test fun backupAgentLists() {+ val agent = AppBackupAgent()+ assertEquals(listOf("minesweeper_stats"), agent.prefNames)+ assertEquals(listOf("datastore_default"), agent.datastoreNames)+ }++ @Test fun routeSerializationRoundTrip() {+ val json = Json+ val game = Route.Game(GameConfig(BoardSize.LARGE, Difficulty.EXPERT))+ val decoded = json.decodeFromString(Route.serializer(), json.encodeToString(Route.serializer(), game))+ assertEquals(game, decoded)+ assertEquals(Route.Home, json.decodeFromString(Route.serializer(), json.encodeToString(Route.serializer(), Route.Home)))+ assertEquals(Route.GameCenter, json.decodeFromString(Route.serializer(), json.encodeToString(Route.serializer(), Route.GameCenter)))+ assertTrue(json.encodeToString(Route.serializer(), game).contains("LARGE"))+ }++ @Test fun gameConfigVariantAndDefaults() {+ assertEquals(GameConfig(BoardSize.MEDIUM, Difficulty.MEDIUM), GameConfig())+ assertEquals("LARGE_EXPERT", GameConfig(BoardSize.LARGE, Difficulty.EXPERT).variant)+ }+}
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModelFlowsTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModelFlowsTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModelFlowsTest.ktnew file mode 100644index 0000000000..569e4bbbae--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModelFlowsTest.kt@@ -0,0 +1,185 @@+package com.vayunmathur.games.minesweeper.platform++import android.app.Application+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.minesweeper.data.BoardSize+import com.vayunmathur.games.minesweeper.data.Difficulty+import com.vayunmathur.games.minesweeper.data.GameConfig+import com.vayunmathur.games.minesweeper.data.GameOutcome+import com.vayunmathur.games.minesweeper.data.MinesweeperStatsRepository+import com.vayunmathur.games.minesweeper.data.TapMode+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Win/lose publishing, chording, mode interplay and give-up accounting. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MinesweeperViewModelFlowsTest {+ private val app = ApplicationProvider.getApplicationContext<Application>()+ private fun vm() = MinesweeperViewModel(app)+ private fun stats() = MinesweeperStatsRepository(app)++ @BeforeTest fun clearPrefs() {+ app.getSharedPreferences("minesweeper_stats", Context.MODE_PRIVATE).edit().clear().commit()+ }++ private fun startedVm(): MinesweeperViewModel {+ val vm = vm()+ vm.newGame(GameConfig(BoardSize.SMALL, Difficulty.EASY))+ vm.tapCell(0)+ assertTrue(vm.uiState.value.game!!.started)+ return vm+ }++ @Test fun winningByRevealingEverySafeCellRecordsWin() {+ val vm = startedVm()+ // Dig every remaining safe cell; cascades do most of the work.+ while (true) {+ val game = vm.uiState.value.game!!+ if (game.isOver) break+ val next = game.revealed.indices.firstOrNull { !game.revealed[it] && !game.mines[it] } ?: break+ vm.tapCell(next)+ }+ val game = vm.uiState.value.game!!+ assertEquals(GameOutcome.WON, game.outcome)+ assertFalse(vm.hasActiveGame())+ val sizeStats = vm.getSizeStats(BoardSize.SMALL)+ assertEquals(1, sizeStats.gamesWon)+ assertEquals(1, sizeStats.gamesPlayed)+ // Taps and timer after the end are ignored.+ val mines = game.mines.indices.first { game.mines[it] }+ vm.tapCell(mines)+ vm.flagCell(mines)+ vm.incrementTimer()+ assertEquals(game, vm.uiState.value.game)+ vm.dismissAchievementNotification()+ }++ @Test fun losingOnAMineRecordsLossAndExplodedCell() {+ // Seed a streak so the loss visibly resets it.+ stats().recordGameWon(BoardSize.SMALL, Difficulty.EASY, 120)+ val vm = startedVm()+ val game = vm.uiState.value.game!!+ val mine = game.mines.indices.first { game.mines[it] && !game.revealed[it] }+ vm.tapCell(mine)+ val lost = vm.uiState.value.game!!+ assertEquals(GameOutcome.LOST, lost.outcome)+ assertEquals(mine, lost.explodedAt)+ assertFalse(vm.hasActiveGame())+ // The pre-seeded win streak is broken by the recorded loss.+ assertEquals(0, stats().getStats(BoardSize.SMALL, Difficulty.EASY).currentWinStreak)+ assertEquals(1, stats().getStats(BoardSize.SMALL, Difficulty.EASY).gamesWon)+ }++ /** Deals fresh fields until the opening cascade leaves a usable chord target. */+ private fun chordTarget(vm: MinesweeperViewModel, minCount: Int): Int {+ repeat(25) {+ vm.newGame(GameConfig(BoardSize.SMALL, Difficulty.EASY))+ vm.tapCell(0)+ val game = vm.uiState.value.game!!+ val idx = game.revealed.indices.firstOrNull { i ->+ game.revealed[i] && game.neighbourCounts[i] >= minCount &&+ game.neighbours(i).any { !game.revealed[it] && !game.mines[it] } &&+ game.neighbours(i).count { game.mines[it] } == game.neighbourCounts[i]+ }+ if (idx != null) return idx+ }+ throw AssertionError("no chord target found in 25 deals")+ }++ @Test fun chordingOpensNeighboursWhenFlagsMatch() {+ val vm = vm()+ val idx = chordTarget(vm, minCount = 1)+ val game = vm.uiState.value.game!!+ val mineNeighbours = game.neighbours(idx).filter { game.mines[it] }+ for (m in mineNeighbours) vm.flagCell(m)+ val before = vm.uiState.value.game!!.revealed.count { it }+ vm.tapCell(idx) // chord+ val after = vm.uiState.value.game!!+ assertTrue(after.revealed.count { it } > before, "chord should open the safe neighbours")+ assertFalse(after.isOver && after.outcome == GameOutcome.LOST)+ }++ @Test fun chordingWithWrongFlagCountDoesNothing() {+ val vm = vm()+ val idx = chordTarget(vm, minCount = 2)+ val game = vm.uiState.value.game!!+ // One correct flag is still fewer than the count: chord must not fire.+ vm.flagCell(game.neighbours(idx).first { game.mines[it] })+ val before = vm.uiState.value.game!!+ vm.tapCell(idx)+ assertEquals(before, vm.uiState.value.game)+ }++ @Test fun flagModeLongPressDigsAndDigModeLongPressFlags() {+ val vm = vm()+ vm.newGame(GameConfig(BoardSize.SMALL, Difficulty.EASY))+ vm.setTapMode(TapMode.FLAG)+ assertEquals(TapMode.FLAG, vm.uiState.value.tapMode)+ // Long press in flag mode is the dig: it lays mines and starts.+ vm.flagCell(40)+ var game = vm.uiState.value.game!!+ assertTrue(game.started)+ assertTrue(game.revealed[40])+ // Back in dig mode, long press flags a hidden cell.+ vm.setTapMode(TapMode.DIG)+ val hidden = game.revealed.indices.first { !game.revealed[it] }+ vm.flagCell(hidden)+ game = vm.uiState.value.game!!+ assertTrue(game.flagged[hidden])+ // Flagging a revealed cell does nothing.+ vm.flagCell(40)+ assertFalse(vm.uiState.value.game!!.flagged[40])+ }++ @Test fun giveUpBeforeStartRecordsNoLossButClearsField() {+ stats().recordGameWon(BoardSize.MEDIUM, Difficulty.MEDIUM, 100)+ val vm = vm()+ vm.newGame(GameConfig()) // MEDIUM/MEDIUM, not started+ vm.giveUp()+ assertNull(vm.uiState.value.game)+ // Streak untouched: the field was never played.+ assertEquals(1, stats().getStats(BoardSize.MEDIUM, Difficulty.MEDIUM).currentWinStreak)+ // Give up with no game at all is also a quiet no-op, keeping config/mode.+ vm.setTapMode(TapMode.FLAG)+ vm.giveUp()+ assertEquals(GameConfig(), vm.uiState.value.config)+ assertEquals(TapMode.FLAG, vm.uiState.value.tapMode)+ }++ @Test fun restartKeepsConfigAndTapModeTimerNeedsStartedGame() {+ val vm = vm()+ vm.newGame(GameConfig(BoardSize.LARGE, Difficulty.EXPERT))+ vm.setTapMode(TapMode.FLAG)+ vm.restart()+ var state = vm.uiState.value+ assertEquals(GameConfig(BoardSize.LARGE, Difficulty.EXPERT), state.config)+ assertEquals(TapMode.FLAG, state.tapMode)+ assertEquals(216, state.game!!.cellCount)+ // Timer does not run before the first dig.+ vm.incrementTimer()+ assertEquals(0, vm.uiState.value.game!!.elapsedSeconds)+ // No game: timer and taps are no-ops.+ vm.giveUp()+ assertNull(vm.uiState.value.game)+ vm.incrementTimer()+ vm.tapCell(0)+ vm.flagCell(0)+ assertNull(vm.uiState.value.game)+ assertFalse(vm.hasActiveGame())+ }++ @Test fun actionsNoopDefaults() {+ val noop = MinesweeperActions.Noop+ noop.tapCell(0); noop.flagCell(0); noop.setTapMode(TapMode.FLAG); noop.restart(); noop.giveUp()+ assertEquals(TapMode.DIG, vm().uiState.value.tapMode)+ }+}
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/HomeAndScreensTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/HomeAndScreensTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/HomeAndScreensTest.ktnew file mode 100644index 0000000000..2c4c580550--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/HomeAndScreensTest.kt@@ -0,0 +1,271 @@+package com.vayunmathur.games.minesweeper.ui++import android.app.Application+import android.content.Context+import androidx.compose.foundation.layout.Column+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.minesweeper.R+import com.vayunmathur.games.minesweeper.Route+import com.vayunmathur.games.minesweeper.data.BoardSize+import com.vayunmathur.games.minesweeper.data.Difficulty+import com.vayunmathur.games.minesweeper.data.GameConfig+import com.vayunmathur.games.minesweeper.data.GameOutcome+import com.vayunmathur.games.minesweeper.data.MinesweeperGameState+import com.vayunmathur.games.minesweeper.data.MinesweeperStatsRepository+import com.vayunmathur.games.minesweeper.data.TapMode+import com.vayunmathur.games.minesweeper.platform.MinesweeperActions+import com.vayunmathur.games.minesweeper.platform.MinesweeperUiState+import com.vayunmathur.games.minesweeper.platform.MinesweeperViewModel+import com.vayunmathur.games.minesweeper.ui.dialogs.GameConfigDialog+import com.vayunmathur.library.util.NavBackStack+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Home, config dialog, display names, game screen, navigation, overlays. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class HomeAndScreensTest {+ @get:Rule val rule = createComposeRule()+ private val ctx get() = ApplicationProvider.getApplicationContext<Context>()+ private fun str(id: Int) = ctx.getString(id)+ private fun uiStr(id: Int) = ctx.getString(id)+ private fun vm() = MinesweeperViewModel(ApplicationProvider.getApplicationContext<Application>())++ @BeforeTest fun clearPrefs() {+ ctx.getSharedPreferences("minesweeper_stats", Context.MODE_PRIVATE).edit().clear().commit()+ }++ private class RecordingActions : MinesweeperActions {+ val calls = mutableListOf<String>()+ var mode: TapMode? = null+ override fun tapCell(index: Int) { calls += "tap:$index" }+ override fun flagCell(index: Int) { calls += "flag:$index" }+ override fun setTapMode(m: TapMode) { mode = m; calls += "mode:$m" }+ override fun restart() { calls += "restart" }+ override fun giveUp() { calls += "giveUp" }+ }++ @Test fun displayNamesAllSizesAndDifficulties() {+ rule.setContent {+ Column {+ androidx.compose.material3.Text(BoardSize.SMALL.displayName())+ androidx.compose.material3.Text(BoardSize.MEDIUM.displayName())+ androidx.compose.material3.Text(BoardSize.LARGE.displayName())+ androidx.compose.material3.Text(Difficulty.EASY.displayName())+ androidx.compose.material3.Text(Difficulty.MEDIUM.displayName())+ androidx.compose.material3.Text(Difficulty.HARD.displayName())+ androidx.compose.material3.Text(Difficulty.EXPERT.displayName())+ }+ }+ rule.onNodeWithText(str(R.string.size_small)).assertIsDisplayed()+ rule.onNodeWithText(str(R.string.size_large)).assertIsDisplayed()+ rule.onNodeWithText(str(R.string.difficulty_expert)).assertIsDisplayed()+ assertEquals(2, rule.onAllNodesWithText(uiStr(com.vayunmathur.library.ui.R.string.medium)).fetchSemanticsNodes().size)+ }++ @Test fun configDialogDefaultsLiveCountAndStart() {+ var started: GameConfig? = null+ rule.setContent {+ GameConfigDialog(initial = GameConfig(), onStart = { started = it }, onDismiss = {})+ }+ rule.onNodeWithText(str(R.string.new_field)).assertIsDisplayed()+ rule.onNodeWithText("21 / 140").assertIsDisplayed()+ // Switch to Small + Easy: 8 mines in 80 cells.+ rule.onNodeWithText(str(R.string.size_small)).performClick()+ rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.easy)).performClick()+ rule.onNodeWithText("8 / 80").assertIsDisplayed()+ rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+ assertEquals(GameConfig(BoardSize.SMALL, Difficulty.EASY), started)+ }++ @Test fun configDialogSeededInitialAndDismiss() {+ var started: GameConfig? = null+ var dismissals = 0+ rule.setContent {+ GameConfigDialog(+ initial = GameConfig(BoardSize.LARGE, Difficulty.EXPERT),+ onStart = { started = it },+ onDismiss = { dismissals++ },+ )+ }+ rule.onNodeWithText("50 / 216").assertIsDisplayed()+ rule.onNodeWithText(str(R.string.size_large)).assertExists()+ rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.back)).performClick()+ assertEquals(1, dismissals)+ assertEquals(null, started)+ }++ @Test fun configDialogDifficultySelectionChangesCount() {+ var started: GameConfig? = null+ rule.setContent {+ GameConfigDialog(initial = GameConfig(BoardSize.SMALL, Difficulty.EASY), onStart = { started = it }, onDismiss = {})+ }+ rule.onNodeWithText(str(R.string.difficulty_expert)).performClick()+ // Expert small: 80 * 0.23 = 18.4 -> 18 mines.+ rule.onNodeWithText("18 / 80").assertIsDisplayed()+ rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+ assertEquals(GameConfig(BoardSize.SMALL, Difficulty.EXPERT), started)+ }++ @Test fun homeStartsNewGameThroughDialog() {+ val vm = vm()+ val backStack = NavBackStack<Route>(arrayOf(Route.Home))+ rule.setContent { HomeScreen(backStack, vm) }+ rule.onNodeWithText("Minesweeper").assertExists()+ // No active game yet: Continue is absent.+ rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.continue_label)).assertDoesNotExist()+ rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+ rule.onNodeWithText(str(R.string.new_field)).assertIsDisplayed()+ // Dialog's New Game button is the second "New Game" node (home's is first).+ val nodes = rule.onAllNodesWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game))+ nodes[nodes.fetchSemanticsNodes().size - 1].performClick()+ assertEquals(Route.Game(GameConfig()), backStack.last())+ assertEquals(140, vm.uiState.value.game!!.cellCount)+ }++ @Test fun homeDismissesDialogWithoutStarting() {+ val vm = vm()+ val backStack = NavBackStack<Route>(arrayOf(Route.Home))+ rule.setContent { HomeScreen(backStack, vm) }+ rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).performClick()+ rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.back)).performClick()+ rule.onNodeWithText(str(R.string.new_field)).assertDoesNotExist()+ assertEquals(Route.Home, backStack.last())+ assertEquals(null, vm.uiState.value.game)+ }++ @Test fun homeContinueResumesAndStatsCardsShowRecords() {+ MinesweeperStatsRepository(ctx).recordGameWon(BoardSize.SMALL, Difficulty.EASY, 75)+ val vm = vm()+ vm.newGame(GameConfig(BoardSize.SMALL, Difficulty.EASY))+ val backStack = NavBackStack<Route>(arrayOf(Route.Home))+ rule.setContent { HomeScreen(backStack, vm) }+ // Small card shows the recorded win and best time.+ rule.onNodeWithText("1/0").assertExists()+ rule.onNodeWithText("01:15").assertExists()+ rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.continue_label)).performClick()+ assertEquals(Route.Game(GameConfig(BoardSize.SMALL, Difficulty.EASY)), backStack.last())+ }++ @Test fun gameScreenDealsWhenNoGameAndKeepsExisting() {+ val vm = vm()+ val backStack = NavBackStack<Route>(arrayOf(Route.Home))+ rule.setContent { GameScreen(backStack, vm, GameConfig(BoardSize.SMALL, Difficulty.EASY)) }+ rule.waitForIdle()+ assertEquals(80, vm.uiState.value.game!!.cellCount)+ rule.onNodeWithText(str(R.string.how_to_play)).assertExists()+ // Recomposing with a different config does not redeal an existing game:+ // the LaunchedEffect is keyed on the config passed at first composition.+ assertEquals(BoardSize.SMALL, vm.uiState.value.config.size)+ }++ @Test fun navigationHomeAndMainActivity() {+ val vm = vm()+ rule.setContent { com.vayunmathur.games.minesweeper.Navigation(vm) }+ rule.onNodeWithText("Minesweeper").assertExists()+ rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.new_game)).assertExists()+ val controller = Robolectric.buildActivity(com.vayunmathur.games.minesweeper.MainActivity::class.java)+ controller.create()+ assertTrue(!controller.get().isFinishing)+ controller.destroy()+ }++ @Test fun boardWonOverlayPlayAgainAndBack() {+ val actions = RecordingActions()+ var exits = 0+ val game = MinesweeperGameState.of(3, 3, 1).copy(+ outcome = GameOutcome.WON, started = true, elapsedSeconds = 42,+ revealed = List(9) { true },+ )+ rule.setContent {+ GameBoardScreen(+ state = MinesweeperUiState(game = game),+ actions = actions,+ onExit = { exits++ },+ )+ }+ rule.onNodeWithText(str(R.string.cleared)).assertIsDisplayed()+ rule.onNodeWithText("${uiStr(com.vayunmathur.library.ui.R.string.game_time)}: 00:42").assertExists()+ rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.game_play_again)).performClick()+ assertTrue(actions.calls.contains("restart"), "${actions.calls}")+ rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.back)).performClick()+ assertEquals(1, exits)+ }++ @Test fun boardLostOverlayHidesTime() {+ val actions = RecordingActions()+ val game = MinesweeperGameState.of(3, 3, 1).copy(+ outcome = GameOutcome.LOST, started = true, elapsedSeconds = 42, explodedAt = 4,+ revealed = List(9) { it == 4 },+ )+ rule.setContent {+ GameBoardScreen(state = MinesweeperUiState(game = game), actions = actions, onExit = {})+ }+ rule.onNodeWithText(str(R.string.boom)).assertIsDisplayed()+ assertTrue(+ rule.onAllNodesWithText("${uiStr(com.vayunmathur.library.ui.R.string.game_time)}: 00:42")+ .fetchSemanticsNodes().isEmpty(),+ )+ }++ @Test fun boardToggleAndImmediateRestartAndGiveUpWithoutProgress() {+ val actions = RecordingActions()+ var exits = 0+ val game = MinesweeperGameState.empty(GameConfig(BoardSize.SMALL, Difficulty.EASY))+ rule.setContent {+ GameBoardScreen(+ state = MinesweeperUiState(config = GameConfig(BoardSize.SMALL, Difficulty.EASY), game = game),+ actions = actions,+ onExit = { exits++ },+ )+ }+ rule.onNodeWithText(str(R.string.mode_flag)).performScrollTo().performClick()+ assertEquals(TapMode.FLAG, actions.mode)+ rule.onNodeWithText(str(R.string.mode_dig)).performScrollTo().performClick()+ assertEquals(TapMode.DIG, actions.mode)+ // Not started: New Field restarts immediately, Give Up exits immediately.+ rule.onNodeWithText(str(R.string.new_field)).performScrollTo().performClick()+ assertTrue(actions.calls.contains("restart"))+ rule.onNodeWithText(str(R.string.give_up)).performScrollTo().performClick()+ assertTrue(actions.calls.contains("giveUp"))+ assertEquals(1, exits)+ }++ @Test fun boardConfirmDialogsWhenGameInProgress() {+ val actions = RecordingActions()+ var exits = 0+ val game = MinesweeperGameState.of(8, 10, 8).copy(started = true, revealed = List(80) { it == 0 })+ rule.setContent {+ GameBoardScreen(+ state = MinesweeperUiState(config = GameConfig(BoardSize.SMALL, Difficulty.EASY), game = game),+ actions = actions,+ onExit = { exits++ },+ )+ }+ // Restart asks first; cancel keeps playing.+ rule.onNodeWithText(str(R.string.new_field)).performScrollTo().performClick()+ rule.onNodeWithText(str(R.string.confirm_new_field_title)).assertIsDisplayed()+ rule.onNodeWithText(uiStr(com.vayunmathur.library.ui.R.string.cancel)).performClick()+ assertTrue(actions.calls.isEmpty(), "${actions.calls}")+ // Give up asks first; confirm gives up and exits.+ rule.onNodeWithText(str(R.string.give_up)).performScrollTo().performClick()+ rule.onNodeWithText(str(R.string.confirm_give_up_title)).assertIsDisplayed()+ val giveUps = rule.onAllNodesWithText(str(R.string.give_up))+ giveUps[giveUps.fetchSemanticsNodes().size - 1].performClick()+ assertTrue(actions.calls.contains("giveUp"))+ assertEquals(1, exits)+ }+}