games-minesweeper: home, picker, board-outcome and stats tests (#tests)
- Commit
20f8973e05de1a618a80f91a2f24e9f22c86a5c8- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 13:21 UTC (20 days ago)
- Parents
a59437f
Wave-3 coverage for :games:minesweeper. The merged report had the home screen, config picker, game screen and half the stats repository at or near zero coverage, so whole user flows (starting a field, resuming one, abandoning one, recording its result) could break without a test noticing. New tests, all asserting real behaviour rather than smoke: - MinesweeperStatsRepositoryTest: per-variant played/won/streak/ best-time recording, loss breaking only the current streak, per-size aggregation and totals, persistence across instances. - FieldGeneratorDenseTest: the too-dense fallback that shrinks the first-tap safe zone to the tapped cell, the exact mine count for every picker combination, and reveal/chord no-op guards returning the same state. - GameConfigDialogTest: live mine-count text as size and density change, start returning the chosen config, dismiss. - HomeScreenTest: stat cards, Continue only with a live field and resuming with its config, the picker hand-off dealing the chosen field and navigating, and cards reflecting a field cleared through the ViewModel. - GameBoardScreenOutcomeTest: win/lose overlays (time shown only on a win), play-again/back, restart and give-up confirmations with cancel, silent restart/give-up on an untouched field, the dig/flag toggle and the negative over-flagged counter, plus the landscape layout. - GameScreenNavigationTest: GameScreen dealing only when no field exists, Navigation landing on home, the Game Center entry, navigation dealing a board, and every display name. - MinesweeperViewModelGameplayTest: full games to a win (mines auto-flagged, win recorded with the clock, timer frozen) and to a loss (streak broken, board frozen), give-up mid-game versus before the first dig, no-game no-ops, flag-mode long press digging, and achievement back-fill from recorded stats. No production code changed and no dead code removed: the only unreferenced-looking class, AppBackupAgent, is instantiated by the framework via android:backupAgent in the manifest. Coverage (merged report, INSTRUCTION): 4762 covered / 2701 missed before, 7163 covered / 300 missed after (+2401). Verified with ./gradlew :games:minesweeper:testDevUnitTest :games:minesweeper:detekt :games:minesweeper:lint without the coverage ignore-failures init: BUILD SUCCESSFUL (91 tests).
Diff
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/data/MinesweeperStatsRepositoryTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/data/MinesweeperStatsRepositoryTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/data/MinesweeperStatsRepositoryTest.ktnew file mode 100644index 0000000000..6feaa8ab02--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/data/MinesweeperStatsRepositoryTest.kt@@ -0,0 +1,133 @@+package com.vayunmathur.games.minesweeper.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Per-variant stats: played/won/streak/best-time recording and the per-size aggregation. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MinesweeperStatsRepositoryTest {++ private val app: Context = ApplicationProvider.getApplicationContext()+ private fun repo() = MinesweeperStatsRepository(app)++ @BeforeTest+ fun clearStats() {+ app.getSharedPreferences("minesweeper_stats", Context.MODE_PRIVATE)+ .edit().clear().commit()+ }++ @Test+ fun untouchedVariantReadsAsEmptyStats() {+ val stats = repo().getStats(BoardSize.LARGE, Difficulty.EXPERT)+ assertEquals(GameStats(), stats)+ assertEquals(Int.MAX_VALUE, stats.bestTimeSeconds)+ assertEquals(GameStats(), repo().getSizeStats(BoardSize.MEDIUM))+ assertEquals(0, repo().getTotalGamesWon())+ assertEquals(0, repo().getBestWinStreak())+ }++ @Test+ fun playedOnlyCountsTheVariantPlayed() {+ val repo = repo()+ repo.recordGamePlayed(BoardSize.SMALL, Difficulty.EASY)+ repo.recordGamePlayed(BoardSize.SMALL, Difficulty.EASY)+ repo.recordGamePlayed(BoardSize.SMALL, Difficulty.HARD)++ assertEquals(2, repo.getStats(BoardSize.SMALL, Difficulty.EASY).gamesPlayed)+ assertEquals(1, repo.getStats(BoardSize.SMALL, Difficulty.HARD).gamesPlayed)+ assertEquals(0, repo.getStats(BoardSize.MEDIUM, Difficulty.EASY).gamesPlayed)+ // Playing alone never touches the win counters.+ val easy = repo.getStats(BoardSize.SMALL, Difficulty.EASY)+ assertEquals(0, easy.gamesWon)+ assertEquals(0, easy.currentWinStreak)+ }++ @Test+ fun winsBuildStreaksAndKeepTheBestTime() {+ val repo = repo()+ repo.recordGameWon(BoardSize.MEDIUM, Difficulty.MEDIUM, 90)+ repo.recordGameWon(BoardSize.MEDIUM, Difficulty.MEDIUM, 45)+ repo.recordGameWon(BoardSize.MEDIUM, Difficulty.MEDIUM, 120)++ val stats = repo.getStats(BoardSize.MEDIUM, Difficulty.MEDIUM)+ assertEquals(3, stats.gamesWon)+ assertEquals(3, stats.currentWinStreak)+ assertEquals(3, stats.bestWinStreak)+ assertEquals(45, stats.bestTimeSeconds, "a slower later win must not erase the best time")+ }++ @Test+ fun aLossResetsTheCurrentStreakButKeepsBestStreakAndWins() {+ val repo = repo()+ repeat(3) { repo.recordGameWon(BoardSize.SMALL, Difficulty.HARD, 30) }+ repo.recordGameLost(BoardSize.SMALL, Difficulty.HARD)++ val stats = repo.getStats(BoardSize.SMALL, Difficulty.HARD)+ assertEquals(0, stats.currentWinStreak)+ assertEquals(3, stats.bestWinStreak)+ assertEquals(3, stats.gamesWon)+ assertEquals(30, stats.bestTimeSeconds)++ // The next win starts a new streak from one, not from the old best.+ repo.recordGameWon(BoardSize.SMALL, Difficulty.HARD, 25)+ val after = repo.getStats(BoardSize.SMALL, Difficulty.HARD)+ assertEquals(1, after.currentWinStreak)+ assertEquals(3, after.bestWinStreak)+ assertEquals(25, after.bestTimeSeconds)+ }++ @Test+ fun sizeStatsSumPlayedAndWonAndTakeBestOfTheRest() {+ val repo = repo()+ repo.recordGamePlayed(BoardSize.LARGE, Difficulty.EASY)+ repo.recordGameWon(BoardSize.LARGE, Difficulty.EASY, 80)+ repo.recordGameWon(BoardSize.LARGE, Difficulty.EASY, 70)+ repo.recordGamePlayed(BoardSize.LARGE, Difficulty.EXPERT)+ repo.recordGamePlayed(BoardSize.LARGE, Difficulty.EXPERT)+ repo.recordGameWon(BoardSize.LARGE, Difficulty.EXPERT, 55)+ // A different size must not leak into the LARGE aggregate.+ repo.recordGameWon(BoardSize.SMALL, Difficulty.EASY, 5)++ val size = repo.getSizeStats(BoardSize.LARGE)+ assertEquals(3, size.gamesPlayed)+ assertEquals(3, size.gamesWon)+ assertEquals(2, size.currentWinStreak, "the best current streak across densities")+ assertEquals(2, size.bestWinStreak)+ assertEquals(55, size.bestTimeSeconds, "the fastest time across densities")+ }++ @Test+ fun totalsSpanEverySizeAndDensity() {+ val repo = repo()+ repo.recordGameWon(BoardSize.SMALL, Difficulty.EASY, 10)+ repo.recordGameWon(BoardSize.SMALL, Difficulty.EASY, 10)+ repo.recordGameWon(BoardSize.MEDIUM, Difficulty.HARD, 10)+ repeat(4) { repo.recordGameWon(BoardSize.LARGE, Difficulty.MEDIUM, 10) }+ repo.recordGameLost(BoardSize.LARGE, Difficulty.MEDIUM)+ repeat(2) { repo.recordGameWon(BoardSize.LARGE, Difficulty.MEDIUM, 10) }++ assertEquals(9, repo.getTotalGamesWon())+ // LARGE/MEDIUM peaked at four in a row before the loss broke the run.+ assertEquals(4, repo.getBestWinStreak())+ }++ @Test+ fun recordsSurviveANewRepositoryInstance() {+ repo().recordGamePlayed(BoardSize.MEDIUM, Difficulty.EXPERT)+ repo().recordGameWon(BoardSize.MEDIUM, Difficulty.EXPERT, 33)++ val reread = repo().getStats(BoardSize.MEDIUM, Difficulty.EXPERT)+ assertEquals(1, reread.gamesPlayed)+ assertEquals(1, reread.gamesWon)+ assertEquals(33, reread.bestTimeSeconds)+ assertTrue(reread.currentWinStreak == 1)+ }+}
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/domain/FieldGeneratorDenseTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/domain/FieldGeneratorDenseTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/domain/FieldGeneratorDenseTest.ktnew file mode 100644index 0000000000..e93b72b648--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/domain/FieldGeneratorDenseTest.kt@@ -0,0 +1,102 @@+package com.vayunmathur.games.minesweeper.domain++import com.vayunmathur.games.minesweeper.data.Difficulty+import com.vayunmathur.games.minesweeper.data.BoardSize+import com.vayunmathur.games.minesweeper.data.GameOutcome+import com.vayunmathur.games.minesweeper.data.MinesweeperGameState+import kotlin.random.Random+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertSame+import kotlin.test.assertTrue++/** Dense-field fallbacks in the generator and no-op guards in the rules. */+class FieldGeneratorDenseTest {++ @Test+ fun safeZoneShrinksToTheTappedCellWhenTheFieldIsTooDense() {+ // 3x3 with eight mines: the full 3x3 safe zone leaves no room for the mines,+ // so only the tapped centre is guaranteed clear and the tap still cannot lose.+ val blank = MinesweeperGameState.of(cols = 3, rows = 3, mineCount = 8)+ val laid = FieldGenerator.lay(blank, safeIndex = 4, rng = Random(7))+ assertEquals(8, laid.mines.count { it })+ assertFalse(laid.mines[4])+ assertTrue(laid.started)+ val opened = MinesweeperRules.reveal(laid, 4)+ assertTrue(opened.outcome != GameOutcome.LOST)+ assertTrue(opened.revealed[4])+ }++ @Test+ fun cornerTapKeepsItsWholeNeighbourhoodClear() {+ val blank = MinesweeperGameState.of(cols = 4, rows = 4, mineCount = 3)+ repeat(25) { seed ->+ val laid = FieldGenerator.lay(blank, safeIndex = 0, rng = Random(seed))+ assertFalse(laid.mines[0], "seed $seed")+ for (n in laid.neighbours(0)) assertFalse(laid.mines[n], "seed $seed neighbour $n")+ assertEquals(3, laid.mines.count { it }, "seed $seed")+ }+ }++ @Test+ fun mineCountsForEveryPickerCombination() {+ assertEquals(8, Difficulty.EASY.mineCount(BoardSize.SMALL))+ assertEquals(12, Difficulty.MEDIUM.mineCount(BoardSize.SMALL))+ assertEquals(15, Difficulty.HARD.mineCount(BoardSize.SMALL))+ assertEquals(18, Difficulty.EXPERT.mineCount(BoardSize.SMALL))+ assertEquals(14, Difficulty.EASY.mineCount(BoardSize.MEDIUM))+ assertEquals(21, Difficulty.MEDIUM.mineCount(BoardSize.MEDIUM))+ assertEquals(27, Difficulty.HARD.mineCount(BoardSize.MEDIUM))+ assertEquals(32, Difficulty.EXPERT.mineCount(BoardSize.MEDIUM))+ assertEquals(22, Difficulty.EASY.mineCount(BoardSize.LARGE))+ assertEquals(32, Difficulty.MEDIUM.mineCount(BoardSize.LARGE))+ assertEquals(41, Difficulty.HARD.mineCount(BoardSize.LARGE))+ assertEquals(50, Difficulty.EXPERT.mineCount(BoardSize.LARGE))+ }++ @Test+ fun revealAndChordGuardsReturnTheSameState() {+ // Mine at centre (4) of a 3x3.+ val mines = List(9) { it == 4 }+ val base = MinesweeperGameState.of(3, 3, 1)+ val counts = List(9) { i -> if (mines[i]) 0 else base.neighbours(i).count { mines[it] } }+ val state = base.copy(mines = mines, neighbourCounts = counts, started = true)++ val flaggedMine = MinesweeperRules.toggleFlag(state, 4)+ assertSame(flaggedMine, MinesweeperRules.reveal(flaggedMine, 4), "a flagged mine cannot be dug")+ assertTrue(flaggedMine.outcome == GameOutcome.PLAYING)++ val opened = MinesweeperRules.reveal(state, 0)+ assertSame(opened, MinesweeperRules.reveal(opened, 0), "re-digging an open cell is a no-op")+ // Cell 0 is a 1 with no flags around it: chording it must open nothing.+ val chordedNoFlags = MinesweeperRules.chord(opened, 0)+ assertEquals(opened.revealed, chordedNoFlags.revealed)+ assertEquals(GameOutcome.PLAYING, chordedNoFlags.outcome)++ // Over-flagging a number also blocks the chord: the count must match exactly.+ val revealedOne = MinesweeperRules.reveal(state, 1)+ val overFlagged = MinesweeperRules.toggleFlag(+ MinesweeperRules.toggleFlag(revealedOne, 0), 2,+ )+ val chorded = MinesweeperRules.chord(overFlagged, 1)+ assertEquals(overFlagged.revealed, chorded.revealed, "two flags around a 1 cannot chord")+ assertEquals(GameOutcome.PLAYING, chorded.outcome)+ }++ @Test+ fun unstartedBlankFieldIsNotClearedAndHasNoProgress() {+ val blank = MinesweeperGameState.of(cols = 5, rows = 4, mineCount = 3)+ assertEquals(20, blank.cellCount)+ assertFalse(blank.isCleared)+ assertFalse(blank.isOver)+ assertEquals(3, blank.minesRemaining)+ assertEquals(-1, blank.explodedAt)+ assertTrue(blank.mines.none { it })+ assertTrue(blank.neighbourCounts.all { it == 0 })+ // A field whose only cells are mines would be trivially cleared; the real+ // layouts always pair mines with covered safe cells, so check the inverse:+ val allSafeRevealed = blank.copy(revealed = List(20) { true })+ assertTrue(allSafeRevealed.isCleared)+ }+}
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModelGameplayTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModelGameplayTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModelGameplayTest.ktnew file mode 100644index 0000000000..826ee23c3a--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModelGameplayTest.kt@@ -0,0 +1,282 @@+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 com.vayunmathur.library.util.AchievementStatus+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+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++/** Full games through the ViewModel: win, loss, give-up, timer and achievement back-fill. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MinesweeperViewModelGameplayTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private fun vm() = MinesweeperViewModel(app)+ private fun statsRepo() = MinesweeperStatsRepository(app)++ @BeforeTest+ fun clearStats() {+ app.getSharedPreferences("minesweeper_stats", Context.MODE_PRIVATE)+ .edit().clear().commit()+ }++ /** Starts a SMALL/EASY field and returns the laid game. */+ private fun started(vm: MinesweeperViewModel): Int {+ vm.newGame(GameConfig(BoardSize.SMALL, Difficulty.EASY))+ vm.tapCell(0)+ return 0+ }++ @Test+ fun diggingEverySafeCellWinsFlagsTheMinesAndRecordsTheWin() {+ val vm = vm()+ vm.newGame(GameConfig(BoardSize.SMALL, Difficulty.EASY))+ vm.tapCell(0)+ vm.incrementTimer()+ vm.incrementTimer()+ playRemaining(vm)++ val game = vm.uiState.value.game!!+ assertEquals(GameOutcome.WON, game.outcome)+ assertTrue(game.isOver)+ assertTrue(game.isCleared)+ assertEquals(0, game.minesRemaining)+ assertEquals(+ game.mines.indices.filter { game.mines[it] },+ game.flagged.indices.filter { game.flagged[it] },+ "winning flags every remaining mine",+ )+ assertFalse(vm.hasActiveGame())++ val sizeStats = vm.getSizeStats(BoardSize.SMALL)+ assertEquals(1, sizeStats.gamesPlayed)+ assertEquals(1, sizeStats.gamesWon)+ assertEquals(1, sizeStats.currentWinStreak)+ assertEquals(2, sizeStats.bestTimeSeconds, "the win is recorded with the clock")++ // The clock stops once the field is over, and dismissing a (possibly+ // queued) achievement notification is always safe.+ vm.incrementTimer()+ assertEquals(2, vm.elapsedSeconds.value)+ vm.dismissAchievementNotification()+ }++ private fun playRemaining(vm: MinesweeperViewModel) {+ var guard = 0+ while (vm.uiState.value.game!!.outcome == GameOutcome.PLAYING && guard++ < 500) {+ val game = vm.uiState.value.game!!+ val next = game.revealed.indices.first { !game.revealed[it] && !game.mines[it] }+ vm.tapCell(next)+ }+ assertTrue(guard < 500, "the field must be clearable by digging safe cells")+ }++ @Test+ fun diggingAMineLosesRecordsTheLossAndFreezesTheBoard() {+ // Seed a win streak on the same variant so the loss has something to break.+ statsRepo().recordGameWon(BoardSize.SMALL, Difficulty.EASY, 30)+ val vm = vm()+ started(vm)+ val laid = vm.uiState.value.game!!+ val mine = laid.mines.indices.first { laid.mines[it] && !laid.revealed[it] }++ vm.tapCell(mine)+ val lost = vm.uiState.value.game!!+ assertEquals(GameOutcome.LOST, lost.outcome)+ assertEquals(mine, lost.explodedAt)+ assertTrue(lost.revealed[mine])+ assertFalse(vm.hasActiveGame())++ val stats = statsRepo().getStats(BoardSize.SMALL, Difficulty.EASY)+ assertEquals(1, stats.gamesPlayed, "the first dig counted the game as played")+ assertEquals(1, stats.gamesWon, "the seeded win is untouched")+ assertEquals(0, stats.currentWinStreak, "the loss breaks the streak")++ // A finished board ignores taps, flags and the clock.+ val safe = lost.revealed.indices.first { !lost.revealed[it] && !lost.mines[it] }+ vm.tapCell(safe)+ assertEquals(lost, vm.uiState.value.game)+ assertFalse(vm.flagCell(safe))+ vm.incrementTimer()+ assertEquals(0, vm.elapsedSeconds.value)++ // Restarting deals a fresh unstarted field on the same variant.+ vm.restart()+ val fresh = vm.uiState.value.game!!+ assertEquals(GameOutcome.PLAYING, fresh.outcome)+ assertFalse(fresh.started)+ assertTrue(fresh.mines.none { it })+ assertTrue(vm.hasActiveGame())+ }++ @Test+ fun giveUpMidGameRecordsALossAndClearsTheField() {+ statsRepo().recordGameWon(BoardSize.MEDIUM, Difficulty.MEDIUM, 30)+ val vm = vm()+ vm.newGame(GameConfig(BoardSize.MEDIUM, Difficulty.MEDIUM))+ vm.tapCell(40)+ vm.incrementTimer()+ assertEquals(1, vm.elapsedSeconds.value)++ vm.giveUp()+ assertNull(vm.uiState.value.game)+ assertFalse(vm.hasActiveGame())+ assertEquals(0, vm.elapsedSeconds.value)+ assertEquals(+ 0,+ statsRepo().getStats(BoardSize.MEDIUM, Difficulty.MEDIUM).currentWinStreak,+ "abandoning a started field breaks the streak",+ )+ }++ @Test+ fun giveUpBeforeTheFirstDigRecordsNothing() {+ statsRepo().recordGameWon(BoardSize.MEDIUM, Difficulty.MEDIUM, 30)+ val vm = vm()+ vm.newGame(GameConfig(BoardSize.MEDIUM, Difficulty.MEDIUM))+ vm.giveUp()+ assertNull(vm.uiState.value.game)+ val stats = statsRepo().getStats(BoardSize.MEDIUM, Difficulty.MEDIUM)+ assertEquals(1, stats.currentWinStreak, "an untouched field is not a loss")+ assertEquals(0, stats.gamesPlayed)++ // Giving up with no field at all is a no-op.+ vm.giveUp()+ assertNull(vm.uiState.value.game)+ }++ @Test+ fun actionsWithoutAGameAreSafeNoOps() {+ val vm = vm()+ assertNull(vm.uiState.value.game)+ assertFalse(vm.hasActiveGame())+ vm.tapCell(3)+ assertFalse(vm.flagCell(3))+ vm.incrementTimer()+ assertEquals(0, vm.elapsedSeconds.value)+ vm.setTapMode(TapMode.FLAG)+ assertEquals(TapMode.FLAG, vm.uiState.value.tapMode)+ vm.dismissAchievementNotification()+ }++ @Test+ fun flagModeLongPressDigsAndTapOnOpenNumberNeverChords() {+ val vm = vm()+ started(vm)+ val laid = vm.uiState.value.game!!+ vm.setTapMode(TapMode.FLAG)++ // A flag-mode tap on an open number must open nothing (chord lives on long press).+ val openNumber = laid.revealed.indices.firstOrNull {+ laid.revealed[it] && laid.neighbourCounts[it] > 0+ }+ if (openNumber != null) {+ val before = vm.uiState.value.game!!+ vm.tapCell(openNumber)+ assertEquals(before, vm.uiState.value.game)+ }++ // A flag-mode long press on a covered safe cell digs it instead of flagging.+ val coveredSafe = vm.uiState.value.game!!.let { g ->+ g.revealed.indices.first { !g.revealed[it] && !g.mines[it] }+ }+ assertFalse(vm.flagCell(coveredSafe), "digging via long press is not a flag change")+ assertTrue(vm.uiState.value.game!!.revealed[coveredSafe])+ }++ @Test+ fun winOnLargeExpertWithoutFlagsStillCountsThroughTheWinPath() {+ val vm = vm()+ vm.newGame(GameConfig(BoardSize.LARGE, Difficulty.EXPERT))+ vm.tapCell(0)+ playRemaining(vm)+ val game = vm.uiState.value.game!!+ assertEquals(GameOutcome.WON, game.outcome)+ assertEquals(216, game.cellCount)+ val stats = statsRepo().getStats(BoardSize.LARGE, Difficulty.EXPERT)+ assertEquals(1, stats.gamesPlayed)+ assertEquals(1, stats.gamesWon)+ }++ @Test+ fun achievementsBackFillFromRecordedStats() {+ val repo = statsRepo()+ runBlocking { vm().achievementsManager.forgetAll() }+ repeat(10) { repo.recordGameWon(BoardSize.SMALL, Difficulty.EASY, 45) }++ val manager = MinesweeperAchievementsManager(+ app,+ app.assets.open("achievements.json").bufferedReader().readText(),+ repo,+ )+ assertEquals(+ listOf(+ "first_win", "win_large", "win_expert", "no_flags_needed", "speed_win",+ "first_chord", "wins_10", "wins_50", "win_streak_5",+ ),+ manager.achievements.map { it.id },+ )+ manager.checkExistingAchievements()++ val statuses = awaitStatuses(manager) { list ->+ val byId = list.associateBy { it.achievement.id }+ byId.getValue("first_win").isUnlocked &&+ byId.getValue("speed_win").isUnlocked &&+ byId.getValue("wins_10").isUnlocked &&+ byId.getValue("win_streak_5").isUnlocked &&+ !byId.getValue("win_large").isUnlocked &&+ !byId.getValue("win_expert").isUnlocked &&+ byId.getValue("wins_50").progress == 10+ }+ val byId = statuses.associateBy { it.achievement.id }+ assertEquals(10, byId.getValue("wins_10").progress)+ assertTrue(byId.getValue("win_streak_5").isUnlocked)+ }++ @Test+ fun achievementsStayLockedWithNoWinsRecorded() {+ val repo = statsRepo()+ val manager = MinesweeperAchievementsManager(+ app,+ app.assets.open("achievements.json").bufferedReader().readText(),+ repo,+ )+ runBlocking { manager.forgetAll() }+ manager.checkExistingAchievements()+ val statuses = runBlocking { manager.getAchievementStatuses().first() }+ assertTrue(statuses.none { it.isUnlocked })+ assertTrue(statuses.all { it.progress == 0 })+ }++ private fun awaitStatuses(+ manager: MinesweeperAchievementsManager,+ condition: (List<AchievementStatus>) -> Boolean,+ ): List<AchievementStatus> {+ val deadline = System.currentTimeMillis() + 20_000+ var last: List<AchievementStatus> = emptyList()+ while (System.currentTimeMillis() < deadline) {+ last = runBlocking { manager.getAchievementStatuses().first() }+ if (condition(last)) return last+ Thread.sleep(50)+ }+ assertTrue(condition(last), "timed out waiting for achievement statuses: $last")+ return last+ }+}
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/GameBoardScreenOutcomeTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/GameBoardScreenOutcomeTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/GameBoardScreenOutcomeTest.ktnew file mode 100644index 0000000000..d4c6e9d698--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/GameBoardScreenOutcomeTest.kt@@ -0,0 +1,208 @@+package com.vayunmathur.games.minesweeper.ui++import android.content.Context+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.minesweeper.R+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.TapMode+import com.vayunmathur.games.minesweeper.platform.MinesweeperActions+import com.vayunmathur.games.minesweeper.platform.MinesweeperUiState+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Board screen end states, confirmation dialogs and the mode toggle. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class GameBoardScreenOutcomeTest {++ @get:Rule val rule = createComposeRule()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int, vararg a: Any) = ctx.getString(id, *a)++ private class RecordingActions : MinesweeperActions {+ val tapped = mutableListOf<Int>()+ var mode: TapMode? = null+ var restarts = 0+ var giveUps = 0+ override fun tapCell(index: Int) { tapped += index }+ override fun flagCell(index: Int): Boolean = false+ override fun setTapMode(m: TapMode) { mode = m }+ override fun restart() { restarts++ }+ override fun giveUp() { giveUps++ }+ }++ /** 3x3, mine at centre (4). */+ private fun field(+ revealed: List<Boolean> = List(9) { false },+ flagged: List<Boolean> = List(9) { false },+ outcome: GameOutcome = GameOutcome.PLAYING,+ started: Boolean = true,+ explodedAt: Int = -1,+ ): MinesweeperGameState {+ val mines = List(9) { it == 4 }+ val probe = MinesweeperGameState.of(3, 3, 1)+ val counts = List(9) { i -> if (mines[i]) 0 else probe.neighbours(i).count { mines[it] } }+ return MinesweeperGameState(+ cols = 3, rows = 3, mineCount = 1, mines = mines, neighbourCounts = counts,+ revealed = revealed, flagged = flagged, outcome = outcome,+ explodedAt = explodedAt, started = started,+ )+ }++ private fun state(game: MinesweeperGameState?) = MinesweeperUiState(+ config = GameConfig(BoardSize.SMALL, Difficulty.EASY), game = game,+ )++ @Test+ fun wonFieldShowsClearedOverlayWithTimeAndPlayAgainRestarts() {+ val actions = RecordingActions()+ var exited = false+ val won = field(+ revealed = List(9) { it != 4 }, flagged = List(9) { it == 4 },+ outcome = GameOutcome.WON,+ )+ rule.setContent {+ GameBoardScreen(state(won), actions, onExit = { exited = true }, elapsedSeconds = { 65 })+ }+ rule.onNodeWithText(str(R.string.cleared)).assertExists()+ rule.onNodeWithText("${str(com.vayunmathur.library.ui.R.string.game_time)}: 01:05")+ .assertExists()+ assertFalse(exited)+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.game_play_again)).performClick()+ assertEquals(1, actions.restarts)+ }++ @Test+ fun lostFieldShowsBoomWithoutTimeAndBackExits() {+ val actions = RecordingActions()+ var exited = false+ val lost = field(+ revealed = List(9) { it == 4 }, outcome = GameOutcome.LOST, explodedAt = 4,+ )+ rule.setContent {+ GameBoardScreen(state(lost), actions, onExit = { exited = true }, elapsedSeconds = { 65 })+ }+ rule.onNodeWithText(str(R.string.boom)).assertExists()+ rule.onNodeWithText("${str(com.vayunmathur.library.ui.R.string.game_time)}: 01:05")+ .assertDoesNotExist()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.game_back)).performClick()+ assertTrue(exited)+ assertEquals(0, actions.restarts)+ }++ @Test+ fun newFieldWithProgressAsksFirstAndCancelKeepsTheField() {+ val actions = RecordingActions()+ var dialogShown: Boolean? = null+ rule.setContent {+ GameBoardScreen(+ state(field(revealed = List(9) { it == 0 })), actions,+ onExit = {}, onDialogShownChange = { dialogShown = it },+ )+ }+ rule.onNodeWithText(str(R.string.new_field)).performClick()+ rule.onNodeWithText(str(R.string.confirm_new_field_title)).assertExists()+ rule.onNodeWithText(str(R.string.confirm_new_field_message)).assertExists()+ assertEquals(true, dialogShown)+ assertEquals(0, actions.restarts)++ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.cancel)).performClick()+ rule.onNodeWithText(str(R.string.confirm_new_field_title)).assertDoesNotExist()+ assertEquals(false, dialogShown)+ assertEquals(0, actions.restarts)++ rule.onNodeWithText(str(R.string.new_field)).performClick()+ rule.onNodeWithText(str(R.string.confirm_new_field_title)).assertExists()+ // Confirm via the dialog's confirm button (last "New Field" node).+ val nodes = rule.onAllNodesWithText(str(R.string.new_field))+ nodes[nodes.fetchSemanticsNodes().lastIndex].performClick()+ assertEquals(1, actions.restarts)+ }++ @Test+ fun giveUpWithProgressAsksFirstAndConfirmEndsTheField() {+ val actions = RecordingActions()+ var exited = false+ rule.setContent {+ GameBoardScreen(+ state(field(revealed = List(9) { it == 0 })), actions,+ onExit = { exited = true },+ )+ }+ rule.onNodeWithText(str(R.string.give_up)).performClick()+ rule.onNodeWithText(str(R.string.confirm_give_up_title)).assertExists()+ rule.onNodeWithText(str(R.string.confirm_give_up_message)).assertExists()+ assertEquals(0, actions.giveUps)+ assertFalse(exited)++ val nodes = rule.onAllNodesWithText(str(R.string.give_up))+ nodes[nodes.fetchSemanticsNodes().lastIndex].performClick()+ assertEquals(1, actions.giveUps)+ assertTrue(exited)+ }++ @Test+ fun giveUpWithoutProgressExitsImmediatelyAndNewFieldRestartsSilently() {+ val actions = RecordingActions()+ var exited = false+ rule.setContent {+ GameBoardScreen(state(field(started = false)), actions, onExit = { exited = true })+ }+ rule.onNodeWithText(str(R.string.new_field)).performClick()+ assertEquals(1, actions.restarts, "an untouched field restarts without asking")+ rule.onNodeWithText(str(R.string.confirm_new_field_title)).assertDoesNotExist()++ rule.onNodeWithText(str(R.string.give_up)).performClick()+ assertEquals(1, actions.giveUps)+ assertTrue(exited, "giving up an untouched field leaves at once")+ rule.onNodeWithText(str(R.string.confirm_give_up_title)).assertDoesNotExist()+ }++ @Test+ fun modeToggleReportsDigAndFlagSelections() {+ val actions = RecordingActions()+ rule.setContent { GameBoardScreen(state(field()), actions, onExit = {}) }+ rule.onNodeWithText(str(R.string.mode_flag)).performClick()+ assertEquals(TapMode.FLAG, actions.mode)+ rule.onNodeWithText(str(R.string.mode_dig)).performClick()+ assertEquals(TapMode.DIG, actions.mode)+ }++ @Test+ fun overFlaggedCounterReadsNegative() {+ val game = field(flagged = List(9) { it == 0 || it == 1 })+ assertEquals(-1, game.minesRemaining)+ rule.setContent { GameBoardScreen(state(game), RecordingActions(), onExit = {}) }+ rule.onNodeWithText("-1", substring = true).assertExists()+ }++ @Test+ @Config(qualifiers = "w800dp-h360dp-land")+ fun landscapeBoardStillOffersControlsAndCells() {+ val game = MinesweeperGameState.empty(GameConfig(BoardSize.LARGE, Difficulty.MEDIUM))+ rule.setContent {+ GameBoardScreen(+ MinesweeperUiState(config = GameConfig(BoardSize.LARGE, Difficulty.MEDIUM), game = game),+ RecordingActions(), onExit = {},+ )+ }+ rule.onNodeWithText(str(R.string.new_field)).assertExists()+ rule.onNodeWithText(str(R.string.give_up)).assertExists()+ rule.onNodeWithContentDescription("Row 18, column 12,", substring = true).assertExists()+ }+}
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/GameScreenNavigationTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/GameScreenNavigationTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/GameScreenNavigationTest.ktnew file mode 100644index 0000000000..ff0397be95--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/GameScreenNavigationTest.kt@@ -0,0 +1,126 @@+package com.vayunmathur.games.minesweeper.ui++import android.app.Application+import android.content.Context+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.minesweeper.Navigation+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.platform.MinesweeperViewModel+import com.vayunmathur.library.util.NavBackStack+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** GameScreen's deal-if-missing behaviour and the top-level Navigation host. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class GameScreenNavigationTest {++ @get:Rule val rule = createComposeRule()+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int) = app.getString(id)+ private fun backStack() = NavBackStack(arrayOf<Route>(Route.Home))++ @BeforeTest+ fun clearStats() {+ app.getSharedPreferences("minesweeper_stats", Context.MODE_PRIVATE)+ .edit().clear().commit()+ }++ @Test+ fun gameScreenDealsAFieldWhenEnteredWithoutOne() {+ val vm = MinesweeperViewModel(app)+ rule.setContent {+ GameScreen(backStack(), vm, GameConfig(BoardSize.SMALL, Difficulty.EASY))+ }+ rule.waitForIdle()+ val game = vm.uiState.value.game+ assertNotNull(game)+ assertEquals(80, game.cellCount)+ rule.onNodeWithText(str(R.string.new_field)).assertExists()+ rule.onNodeWithText(str(R.string.give_up)).assertExists()+ }++ @Test+ fun gameScreenKeepsAFieldAlreadyInProgress() {+ val vm = MinesweeperViewModel(app)+ vm.newGame(GameConfig(BoardSize.LARGE, Difficulty.HARD))+ vm.tapCell(0)+ val before = vm.uiState.value.game+ rule.setContent {+ GameScreen(backStack(), vm, GameConfig(BoardSize.SMALL, Difficulty.EASY))+ }+ rule.waitForIdle()+ // Entering the route must not redeal over a live field, whatever the route carries.+ assertEquals(before, vm.uiState.value.game)+ assertEquals(216, vm.uiState.value.game!!.cellCount)+ }++ @Test+ fun navigationLandsOnHomeWithStatsAndNewGame() {+ val vm = MinesweeperViewModel(app)+ rule.setContent { Navigation(vm) }+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.new_game)).assertExists()+ rule.onAllNodesWithText("0/0").fetchSemanticsNodes().let { assertEquals(3, it.size) }+ }++ @Test+ fun navigationOpensGameCenterAndBackReturnsHome() {+ val vm = MinesweeperViewModel(app)+ rule.setContent { Navigation(vm) }+ rule.onNodeWithContentDescription("Badges").performClick()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.title_game_center))+ .assertExists()+ rule.onNodeWithText("Swept").assertExists()+ }++ @Test+ fun navigationNewGameDealsAndShowsTheBoard() {+ val vm = MinesweeperViewModel(app)+ rule.setContent { Navigation(vm) }+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.new_game)).performClick()+ rule.onNodeWithText(str(R.string.field_size)).assertExists()+ val startButtons = rule.onAllNodesWithText(str(com.vayunmathur.library.ui.R.string.new_game))+ startButtons[startButtons.fetchSemanticsNodes().lastIndex].performClick()+ rule.waitForIdle()+ assertNotNull(vm.uiState.value.game)+ assertTrue(vm.hasActiveGame())+ rule.onNodeWithText(str(R.string.give_up)).assertExists()+ }++ @Test+ fun displayNamesCoverEverySizeAndDifficulty() {+ rule.setContent {+ androidx.compose.foundation.layout.Column {+ BoardSize.entries.forEach { androidx.compose.material3.Text(it.displayName()) }+ Difficulty.entries.forEach { androidx.compose.material3.Text(it.displayName()) }+ }+ }+ rule.onNodeWithText(str(R.string.size_small)).assertExists()+ rule.onNodeWithText(str(R.string.size_large)).assertExists()+ rule.onNodeWithText(str(R.string.difficulty_expert)).assertExists()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.easy)).assertExists()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.hard)).assertExists()+ // Medium is shared by a size and a difficulty.+ assertEquals(+ 2,+ rule.onAllNodesWithText(str(com.vayunmathur.library.ui.R.string.medium))+ .fetchSemanticsNodes().size,+ )+ }+}
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/HomeScreenTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/HomeScreenTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/HomeScreenTest.ktnew file mode 100644index 0000000000..0d3b21e0da--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/HomeScreenTest.kt@@ -0,0 +1,135 @@+package com.vayunmathur.games.minesweeper.ui++import android.app.Application+import android.content.Context+import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasText+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.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.platform.MinesweeperViewModel+import com.vayunmathur.library.util.NavBackStack+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertNull+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Home: stat cards per size, Continue only with a live field, config dialog hand-off. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class HomeScreenTest {++ @get:Rule val rule = createComposeRule()+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int) = app.getString(id)+ private fun backStack() = NavBackStack(arrayOf<Route>(Route.Home))++ @BeforeTest+ fun clearStats() {+ app.getSharedPreferences("minesweeper_stats", Context.MODE_PRIVATE)+ .edit().clear().commit()+ }++ @Test+ fun homeShowsNewGameAndEmptyStatCardsWithoutContinue() {+ val vm = MinesweeperViewModel(app)+ rule.setContent { HomeScreen(backStack(), vm) }++ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.new_game)).assertExists()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.continue_label))+ .assertDoesNotExist()+ rule.onAllNodesWithText("0/0").assertCountEquals(3)+ rule.onAllNodesWithText(str(R.string.cleared_count)).assertCountEquals(3)+ rule.onNodeWithText(str(R.string.size_small)).assertExists()+ rule.onNodeWithText(str(R.string.size_large)).assertExists()+ }++ @Test+ fun continueResumesTheActiveGameWithItsConfig() {+ val vm = MinesweeperViewModel(app)+ vm.newGame(GameConfig(BoardSize.LARGE, Difficulty.HARD))+ val stack = backStack()+ rule.setContent { HomeScreen(stack, vm) }++ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.continue_label))+ .assertExists().performClick()+ assertEquals(2, stack.backStack.size)+ val route = assertIs<Route.Game>(stack.backStack.last())+ assertEquals(GameConfig(BoardSize.LARGE, Difficulty.HARD), route.config)+ }++ @Test+ fun newGameOpensThePickerAndDismissingItDealsNothing() {+ val vm = MinesweeperViewModel(app)+ val stack = backStack()+ rule.setContent { HomeScreen(stack, vm) }++ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.new_game)).performClick()+ rule.onNodeWithText(str(R.string.field_size)).assertExists()+ rule.onNodeWithText("21 / 140").assertExists()+ assertEquals(1, stack.backStack.size)+ assertNull(vm.uiState.value.game)++ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.back)).performClick()+ rule.onNodeWithText(str(R.string.field_size)).assertDoesNotExist()+ assertEquals(1, stack.backStack.size)+ assertNull(vm.uiState.value.game)+ }++ @Test+ fun startingFromThePickerDealsTheChosenFieldAndNavigates() {+ val vm = MinesweeperViewModel(app)+ val stack = backStack()+ rule.setContent { HomeScreen(stack, vm) }++ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.new_game)).performClick()+ // "Large" also labels a home stat card; the picker's segment is the clickable one.+ rule.onNode(hasText(str(R.string.size_large)) and hasClickAction()).performClick()+ rule.onNodeWithText(str(R.string.difficulty_expert)).performClick()+ rule.onNodeWithText("50 / 216").assertExists()+ // The picker is a dialog over the home button of the same label; the+ // dialog's start button is the last matching node in the tree.+ val startButtons = rule.onAllNodesWithText(str(com.vayunmathur.library.ui.R.string.new_game))+ startButtons[startButtons.fetchSemanticsNodes().lastIndex].performClick()++ assertEquals(2, stack.backStack.size)+ val route = assertIs<Route.Game>(stack.backStack.last())+ assertEquals(GameConfig(BoardSize.LARGE, Difficulty.EXPERT), route.config)+ val game = vm.uiState.value.game+ assertEquals(216, game?.cellCount)+ assertEquals(GameOutcome.PLAYING, game?.outcome)+ }++ @Test+ fun statCardsReflectAFieldClearedThroughTheViewModel() {+ val vm = MinesweeperViewModel(app)+ vm.newGame(GameConfig(BoardSize.SMALL, Difficulty.EASY))+ vm.tapCell(0)+ var guard = 0+ while (vm.uiState.value.game!!.outcome == GameOutcome.PLAYING && guard++ < 500) {+ val game = vm.uiState.value.game!!+ val next = game.revealed.indices.first { !game.revealed[it] && !game.mines[it] }+ vm.tapCell(next)+ }+ assertEquals(GameOutcome.WON, vm.uiState.value.game!!.outcome)++ rule.setContent { HomeScreen(backStack(), vm) }+ // SMALL was played once and cleared once; the other sizes stay at 0/0.+ rule.onAllNodesWithText("1/1").assertCountEquals(1)+ rule.onAllNodesWithText("0/0").assertCountEquals(2)+ }+}
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/dialogs/GameConfigDialogTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/dialogs/GameConfigDialogTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/dialogs/GameConfigDialogTest.ktnew file mode 100644index 0000000000..07b6fe55c9--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/ui/dialogs/GameConfigDialogTest.kt@@ -0,0 +1,99 @@+package com.vayunmathur.games.minesweeper.ui.dialogs++import android.content.Context+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.test.core.app.ApplicationProvider+import com.vayunmathur.games.minesweeper.R+import com.vayunmathur.games.minesweeper.data.BoardSize+import com.vayunmathur.games.minesweeper.data.Difficulty+import com.vayunmathur.games.minesweeper.data.GameConfig+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** The size/density picker: live mine count, selection state, start and dismiss. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class GameConfigDialogTest {++ @get:Rule val rule = createComposeRule()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int) = ctx.getString(id)++ @Test+ fun showsLabelsAndLiveMineCountForTheInitialConfig() {+ rule.setContent {+ GameConfigDialog(GameConfig(BoardSize.MEDIUM, Difficulty.MEDIUM), onStart = {}, onDismiss = {})+ }+ rule.onNodeWithText(str(R.string.new_field)).assertExists()+ rule.onNodeWithText(str(R.string.field_size)).assertExists()+ rule.onNodeWithText(str(R.string.difficulty)).assertExists()+ // MEDIUM/MEDIUM: 21 mines in 140 cells.+ rule.onNodeWithText("21 / 140").assertExists()+ rule.onNodeWithText(str(R.string.size_small)).assertExists()+ rule.onNodeWithText(str(R.string.size_large)).assertExists()+ rule.onNodeWithText(str(R.string.difficulty_expert)).assertExists()+ }++ @Test+ fun changingSizeAndDensityUpdatesTheCountAndStartReturnsTheChoice() {+ var started: GameConfig? = null+ rule.setContent {+ GameConfigDialog(+ GameConfig(BoardSize.MEDIUM, Difficulty.MEDIUM),+ onStart = { started = it },+ onDismiss = {},+ )+ }+ rule.onNodeWithText(str(R.string.size_large)).performClick()+ // LARGE with MEDIUM density: 32 mines in 216 cells.+ rule.onNodeWithText("32 / 216").assertExists()+ rule.onNodeWithText(str(R.string.difficulty_expert)).performClick()+ // LARGE/EXPERT: 50 mines in 216 cells.+ rule.onNodeWithText("50 / 216").assertExists()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.easy)).performClick()+ rule.onNodeWithText("22 / 216").assertExists()+ rule.onNodeWithText(str(R.string.size_small)).performClick()+ // SMALL/EASY: 8 mines in 80 cells.+ rule.onNodeWithText("8 / 80").assertExists()++ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.new_game)).performClick()+ assertEquals(GameConfig(BoardSize.SMALL, Difficulty.EASY), started)+ }++ @Test+ fun dismissReportsBackWithoutStarting() {+ var started: GameConfig? = null+ var dismissed = false+ rule.setContent {+ GameConfigDialog(+ GameConfig(BoardSize.LARGE, Difficulty.EXPERT),+ onStart = { started = it },+ onDismiss = { dismissed = true },+ )+ }+ rule.onNodeWithText("50 / 216").assertExists()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.back)).performClick()+ assertNull(started)+ assertEquals(true, dismissed)+ }++ @Test+ fun everySizeAndDensitySegmentIsOffered() {+ rule.setContent {+ GameConfigDialog(GameConfig(), onStart = {}, onDismiss = {})+ }+ // Medium is both a size and a density label, so it appears twice.+ rule.onAllNodesWithText(str(com.vayunmathur.library.ui.R.string.medium))+ .fetchSemanticsNodes().let { assertEquals(2, it.size) }+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.hard)).assertExists()+ rule.onNodeWithText(str(com.vayunmathur.library.ui.R.string.easy)).assertExists()+ }+}