2016-10-26 3 views
0

그 시점까지 stderr에 무엇인가가 인쇄 된 경우 Java 프로그램을 검사하는 방법이 있습니까? (전용 애플리케이션 자체의 일부로서, 테스트 셋업의 일부로 의뢰 있지만) 더미 예로Java 프로그램에서 'stderr'이 비어 있는지 확인

if (something == somethingElse) 
{ 
    System.err.println("This is a message"); 
} 

// Here, I want to check if stderr is empty, or if something was printed to it 
+1

Stderr는 내부 상태를 노출시키지 않는 쓰기 전용 채널입니다. 다른 방법으로 상태를 유지하십시오. – user2864740

답변

2

물론, 이것은 가능하다.

System.errPrintStream으로 리디렉션 할 수 있습니다. 해당 PrintStream 버퍼에 출력을 캡처하는 경우 나중에 해당 버퍼를 확인할 수 있습니다.

@ElliotFrisch가 제안했듯이 원래 오류 스트림의 출력도보고 싶다면 더 많은 작업을해야합니다. 출력을 원래 System.err로 출력하는 사용자 정의 PrintStream 하위 클래스를 만들어야합니다. 버퍼에 관해서.

그러나 단위 테스트를위한 출력을 캡처하는 것이면 아마 필요하지 않을 것입니다. 아마도 출력에 무언가가 포함되어 있다고 주장하고 싶을 것입니다.

// Set up alternate System.err PrintStream that prints to a buffer 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    PrintStream p = new PrintStream(bytes, true, "UTF-8"); 
    System.setErr(p); 

    if (something == somethingElse) { 
     System.err.println("This is a message"); 
    } 

    // Here, I want to check if stderr is empty, or if something was printed 
    // to it 

    // Capture what was printed so far 
    String printedSoFar = bytes.toString("UTF-8"); 
+0

매우 도움이되는 대답입니다. 빠른 후속 조치 - printedSoar 문자열을 사용한 후 System.err을 원래 스트림으로 다시 리디렉션하는 방법은 무엇입니까? –

+1

@MadhavDatt 원래 PrintStream을 변수'PrintStream savedSystemErr = System.err; '에 저장하고 나중에'System.setErr (savedSystemErr); –

관련 문제