Skip to content

Instantly share code, notes, and snippets.

@peterkeller
Created April 24, 2021 13:11
Show Gist options
  • Save peterkeller/288326144913d84deac73272c0618297 to your computer and use it in GitHub Desktop.
Save peterkeller/288326144913d84deac73272c0618297 to your computer and use it in GitHub Desktop.
Catches STDOUT and writes it into a string
public static String catchStdout(Runnable runnable) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStream));
runnable.run();
return outputStream.toString();
}
@Test
void testCatchStdout() {
String s = "Hello, World";
assertEquals(s + "\n", catchStdout(() -> System.out.println(s)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment