Last active
August 8, 2022 13:24
-
-
Save ClausPolanka/b7d1c73f79c51d9f10329695f5c76c61 to your computer and use it in GitHub Desktop.
How to replace System.in and System.out in JUnit tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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