This repository was archived by the owner on Dec 23, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameLauncherTest.java
More file actions
293 lines (251 loc) · 9.61 KB
/
GameLauncherTest.java
File metadata and controls
293 lines (251 loc) · 9.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* JUnit 5 test class for the GameLauncher.
* Uses constructor injection and simulates console I/O to test
* menu interaction, input validation, history recording, and file saving.
* @version 3
*/
public class GameLauncherTest {
/** Captures standard output for test assertions. */
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
/** Stores the original System.out stream for restoration. */
private final PrintStream originalOut = System.out;
/** Stores the original System.in stream for restoration. */
private InputStream originalIn;
/** List of stubbed games to inject into the launcher. */
private List<Game> testGames;
/** In-memory history tracker to inject. */
private GameHistoryTracker testHistory;
/** GameLauncher under test with injected components. */
private GameLauncher launcher;
/** Temporary filename used for history file output. */
private String tempHistoryFileName;
/**
* Set up test environment, redirect I/O, and initialize dependencies.
*/
@BeforeEach
public void setUp() {
System.setOut(new PrintStream(outContent));
originalIn = System.in;
testGames = new ArrayList<>();
testGames.add(new StubGame("Test Game 1", Optional.of(42)));
testGames.add(new StubGame("Test Game 2", Optional.empty()));
testHistory = new GameHistoryTracker();
}
/**
* Restores original console input and output streams.
*/
@AfterEach
public void tearDown() {
System.setOut(originalOut);
System.setIn(originalIn);
}
/**
* Tests normal game selection and exit from the launcher.
*
* @param tempDir Temporary directory for test files
*/
@Test
public void testRunValidGameSelection(@TempDir final Path tempDir) {
provideInput("1\n0\n", tempDir); // Select game 1, then exit.
launcher.run();
String output = outContent.toString();
assertTrue(output.contains("Test Game 1"), "Game name should appear in menu");
assertTrue(output.contains("Playing Test Game 1"), "Game should be played");
assertTrue(output.contains("Goodbye!"), "Exit message should be shown");
}
/**
* Tests non-numeric input handling.
*
* @param tempDir Temporary directory for test files
*/
@Test
public void testRunInvalidInput(@TempDir final Path tempDir) {
provideInput("abd\n0\n", tempDir);
launcher.run();
String output = outContent.toString();
assertTrue(output.contains("Please enter a valid number or Letters H"),
"Should reject non-numeric input");
}
/**
* Simulates out-of-range numeric input and verifies error message.
*
* @param tempDir Temporary directory for test files
*/
@Test
public void testRunInvalidGameChoice(@TempDir final Path tempDir) {
provideInput("999\n0\n", tempDir);
launcher.run();
String output = outContent.toString();
assertTrue(output.contains("Invalid choice."),
"Should handle invalid game number");
}
/**
* Simulates user choosing to view history and verifies output.
*
* @param tempDir Temporary directory for test files
*/
@Test
public void testRunViewHistory(@TempDir final Path tempDir) {
provideInput("H\n0\n", tempDir);
launcher.run();
String output = outContent.toString();
assertTrue(output.contains("=== Game Play History ==="),
"Should display history header");
}
/**
* Verifies that {@code saveHistory()} creates a file and writes data.
*
* @param tempDir Temporary directory for test output
* @throws IOException if file handling fails
*/
@Test
public void testSaveHistoryCreatesFile(@TempDir final Path tempDir) throws IOException {
Path file = tempDir.resolve("testHistory.dat");
testHistory.recordPlay("Test Game C", 56);
testHistory.saveHistory(file.toString());
assertTrue(Files.exists(file),
"Saved history file should exist");
assertTrue(Files.size(file) > 0,
"Saved history file should not be empty");
}
/**
* Verifies that {@code saveHistory()} handles exceptions gracefully.
*
* @param tempDir Temporary directory for test output
*/
@Test
public void testSaveHistoryHandlesIOException(@TempDir final Path tempDir) {
String dummyFile = tempDir.resolve("ignored.dat").toString();
GameLauncher faultyLauncher = new GameLauncher(
new Scanner(new ByteArrayInputStream("0\n".getBytes())),
testHistory,
testGames,
dummyFile
) {
@Override
protected void saveHistory() {
try {
throw new IOException("Simulated IO failure");
} catch (IOException e) {
System.out.println("game history save failed: " + e.getMessage());
}
}
};
faultyLauncher.saveHistory();
String output = outContent.toString();
assertTrue(output.contains("game history save failed: Simulated IO failure"));
}
/**
* Verifies that {@code saveHistory()} persists data after {@code run()} ends.
*
* @param tempDir Temporary directory for test output
* @throws IOException if file handling fails
*/
@Test
public void testHistoryFileSavedAfterRun(@TempDir final Path tempDir) throws IOException {
Path tempHistoryFile = tempDir.resolve("test_history_output.dat");
tempHistoryFileName = tempHistoryFile.toString();
GameLauncher gLauncher = new GameLauncher(
new Scanner(new ByteArrayInputStream("1\n0\n".getBytes())),
testHistory,
testGames,
tempHistoryFileName
);
gLauncher.run();
gLauncher.saveHistory();
assertTrue(Files.exists(tempHistoryFile));
assertTrue(Files.size(tempHistoryFile) > 0);
}
/**
* Replaces System.in with test input, creates launcher with injected scanner.
*
* @param input Input string to simulate via Scanner
* @param tempDir Directory to store temporary history file
*/
private void provideInput(final String input, final Path tempDir) {
ByteArrayInputStream in = new ByteArrayInputStream(input.getBytes());
System.setIn(in);
Scanner scanner = new Scanner(System.in);
tempHistoryFileName = tempDir.resolve("testHistory.dat").toString();
launcher = new GameLauncher(scanner, testHistory, testGames, tempHistoryFileName);
}
/**
* Tests to see if Clear History can be selected by user.
* @param tempDir Derectory to store temporary history file
*/
@Test
public void testClearHistoryInput(@TempDir final Path tempDir) {
provideInput("C\nClear\n0\n", tempDir);
launcher.run();
String output = outContent.toString();
assertTrue(output.contains("Are you sure"),
"Should display history header.");
}
/**
* Tests to see if Save file is cleared for clearHistory
* @param tempDir Derectory to store temporary history file
*/
@Test
public void testClearHistorySaveFile(@TempDir final Path tempDir) throws IOException {
Path tempHistoryFile
= tempDir.resolve("test_history_output.dat");
tempHistoryFileName = tempHistoryFile.toString();
GameLauncher gLauncher = new GameLauncher(
new Scanner(new ByteArrayInputStream("1\n2\n1\n0\n".getBytes())),
testHistory,
testGames,
tempHistoryFileName
);
gLauncher.run();
gLauncher.saveHistory();
System.out.println(Files.size(tempHistoryFile));
testHistory.clearHistory(tempHistoryFileName);
assertTrue(Files.exists(tempHistoryFile),
"File should exists." + Files.size(tempHistoryFile));
assertTrue(Files.size(tempHistoryFile) == 150,
"File should be 150. File size is: " + Files.size(tempHistoryFile));
}
/**
* Stub implementation of the Game interface used for testing.
*/
private static class StubGame implements Game {
/** Name of the game for menu and history. */
private final String name;
/** Predefined score or absence thereof. */
private final Optional<Integer> scoreToReturn;
/**
* Constructs a stubbed game with a fixed name and play result.
* @param gameName display-name of the game
* @param score Optional score
*/
StubGame(final String gameName, final Optional<Integer> score) {
this.name = gameName;
this.scoreToReturn = score;
}
@Override
public String getName() {
return name;
}
@Override
public Optional<Integer> play() {
System.out.println("Playing " + name);
return scoreToReturn;
}
}
}