Skip to content

Instantly share code, notes, and snippets.

@ClausPolanka
Last active August 8, 2022 13:24
Show Gist options
  • Save ClausPolanka/b7d1c73f79c51d9f10329695f5c76c61 to your computer and use it in GitHub Desktop.
Save ClausPolanka/b7d1c73f79c51d9f10329695f5c76c61 to your computer and use it in GitHub Desktop.
How to replace System.in and System.out in JUnit tests
private final InputStream systemIn = System.in;
private final PrintStream systemOut = System.out;
private ByteArrayInputStream testIn;
private ByteArrayOutputStream testOut;
@BeforeEach
public void setUpOutput() {
testOut = new ByteArrayOutputStream();
System.setOut(new PrintStream(testOut));
}
@AfterEach
public void restoreSystemInputOutput() {
System.setIn(systemIn);
System.setOut(systemOut);
}
@Test
void iteration_1() throws FileNotFoundException {
testIn = new ByteArrayInputStream("Hello!".getBytes());
System.setIn(testIn);
Main.main(new String[0]);
assertEquals("Hello!", testOut.toString());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment