물론, 이것은 가능하다.
System.err
을 PrintStream
으로 리디렉션 할 수 있습니다. 해당 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");
Stderr는 내부 상태를 노출시키지 않는 쓰기 전용 채널입니다. 다른 방법으로 상태를 유지하십시오. – user2864740