Aquí está la solución en lugar de ByteArrayOutputStream. No agrega nada a la idea de System.setOut. Más bien, quiero compartir la implementación que es mejor que capturar todo en ByteArrayOutputStream. Prefiero capturar solo la información seleccionada y dejar que todos los mensajes de registro aparezcan en la consola a medida que se registran en lugar de capturar todo en un portada (¿de qué tamaño?) Para su posterior procesamiento.
/**
* Once started, std output is redirected to this thread.
* Thread redirects all data to the former system.out and
* captures some strings.*/
static abstract class OutputCaputre extends Thread {
// overrdie these methods for System.err
PrintStream getDownstream() { return System.out;}
void restoreDownstream() { System.setOut(downstream);}
// will be called for every line in the log
protected abstract void userFilter(String line);
final PrintStream downstream;
public final PipedInputStream pis;
private final PipedOutputStream pos;
OutputCaputre() throws IOException {
downstream = getDownstream();
pos = new PipedOutputStream();
pis = new PipedInputStream(pos);
System.setOut(new PrintStream(pos));
start();
}
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(pis));
// once output is resotred, we must terminate
while (true) {
String line = br.readLine();
if (line == null) {
return;
}
downstream.println(line);
userFilter(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void terminate() throws InterruptedException, IOException {
restoreDownstream(); // switch back to std
pos.close(); // there will be no more data - signal that
join(); // and wait until capture completes
}
};
Aquí se muestra un ejemplo de la utilización de la clase:
OutputCaputre outputCapture = new OutputCaputre() {
protected void userFilter(String line) {
downstream.println("Capture: " + line);
}
};
System.out.println("do you see me captured?");
// here is your test
outputCapture.terminate(); // finally, stop capturing
@dfa, no estoy de acuerdo. Es similar pero lo suficientemente diferente. –
... concedida la respuesta es la misma ... –
El otro hilo ahora tiene una mejor respuesta. Implica el uso de la regla del sistema jUnit StandardOutputStreamLog. También hay reglas del sistema para stderr y stdin. –