Redirecting stdOut in Groovy

Groovy (programming language)
Image via Wikipedia

I am adding this because – while it is out there on the web – it took me some time to find it and I suppose this helps make it more visible in search engines.

I was writing a Groovy unit test for a void function that normally would print to the screen. The only simple way to test would be to redirect stdOut to a string and then test the string.

This is the (or one) way to do it:

public void testPrint() {
//based on solution on
//redirect stdOut and check string is formatted
def bufStr = new ByteArrayOutputStream()
def oldStdOut = System.out;
def newStdOut = new PrintStream(bufStr)
System.out = newStdOut
System.out = oldStdOut
String prtTestStr = bufStr.toString()



Comments are closed.