@Test public void interceptStdout() throws Exception { String result = ConsoleInterceptor.copyOut(() ->{ System.out.print("hello world"); System.out.print('!'); System.out.println(); System.out.println("foobar"); }); assertEquals("hello world!\nfoobar\n", result); result = ConsoleInterceptor.copyOut( () ->{ System.out.print("hello"); System.out.println(" world!"); }); assertEquals("hello world!\n", result); result = ConsoleInterceptor.copyOut( () ->{ System.out.print(58387); System.out.println(" world!"); }); assertEquals("58387 world!\n", result); }
public static String copyOut(Block block) throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final PrintStream printStream = new PrintStream(bos, true); PrintStream oldStream = System.out; PrintStream oldErr = System.err; System.setOut(printStream); System.setErr(printStream); try { block.call(); } finally { System.setOut(oldStream); System.setErr(oldErr); } return bos.toString(); }
ConsoleInterceptor { public static String copyOut(Block block) throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final PrintStream printStream = new PrintStream(bos, true); PrintStream oldStream = System.out; PrintStream oldErr = System.err; System.setOut(printStream); System.setErr(printStream); try { block.call(); } finally { System.setOut(oldStream); System.setErr(oldErr); } return bos.toString(); } }
ConsoleInterceptor { public static String copyOut(Block block) throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final PrintStream printStream = new PrintStream(bos, true); PrintStream oldStream = System.out; PrintStream oldErr = System.err; System.setOut(printStream); System.setErr(printStream); try { block.call(); } finally { System.setOut(oldStream); System.setErr(oldErr); } return bos.toString(); }  }
ConsoleInterceptor { public static String copyOut(Block block) throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final PrintStream printStream = new PrintStream(bos, true); PrintStream oldStream = System.out; PrintStream oldErr = System.err; System.setOut(printStream); System.setErr(printStream); try { block.call(); } finally { System.setOut(oldStream); System.setErr(oldErr); } return bos.toString(); }  static String copyOut(Block block); }
ConsoleInterceptor { public static String copyOut(Block block) throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final PrintStream printStream = new PrintStream(bos, true); PrintStream oldStream = System.out; PrintStream oldErr = System.err; System.setOut(printStream); System.setErr(printStream); try { block.call(); } finally { System.setOut(oldStream); System.setErr(oldErr); } return bos.toString(); }  static String copyOut(Block block);  }