I'm writing a test and I want to capture the messages sent on STDOUT by the tested method. Here is my code:
@Test
public void testAction() throws IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException,
CmdLineException, IOException {
PrintStream originalSTDOUT = System.out;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
try {
System.setOut(ps);
// Call to the method that will print text to STDOUT...
ps.flush();
String batchLog = baos.toString("UTF-8");
assertTrue("Invalid exception text !", batchLog.contains("my expected text..."));
} finally {
System.setOut(originalSTDOUT);//Restore original STDOUT
originalSTDOUT.write(baos.toByteArray());// Write back to STDOUT, even if I comment this line, outputs go to STDOUT...
ps.close();
}
}
Unfortunately, batchLog
is always empty although I can still read the expected text to STDOUT.
The method that will print text to STDOUT in fact catch an exception. It then passes it to a Logger
like below:
log.warn("An error has occured:", e);
where e
is the exception raised in the method I call in my test.
The Logger
uses this appender for printing its messages: org.apache.log4j.ConsoleAppender
. No special configuration is applied to this appender.
What am I missing ?
P.S.:
This SO answer is interesting but it doesn't work for me since the ConsoleAppender
is already created before the StandardOutputStreamLog rule can act.
Java 6
Junit 4.10