確かに、それが可能です。
System.err
を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は、内部状態を公開しないWRITE ONLYチャネルです。状態を別の方法で維持する。 – user2864740