2014년 10월 27일 월요일

System.out 캡쳐

public class StdoutCaptureTest {

 private PrintStream orgStdout;
 private ByteArrayOutputStream capturedOutputStream = new ByteArrayOutputStream();

 @Before
 public void before() {
  orgStdout = System.out;
  PrintStream capturable = new PrintStream(capturedOutputStream);
  System.setOut(capturable);
 }

 @After
 public void after() {
  restoreStdout();
 }
 
 @Test
 public void test() {
  System.out.print("hi");
  restoreStdout();
  String captured = capturedOutputStream.toString();
  System.out.println("from captured : "+captured);
  assertEquals("hi", captured);
 }

 private void restoreStdout() {
  if(orgStdout!=null) {
   System.setOut(orgStdout);
  }
 }
}

댓글 없음:

댓글 쓰기