Skip to content

Instantly share code, notes, and snippets.

@peterkeller
Created April 24, 2021 13:11
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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