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 stackoverflow.com
//redirect stdOut and check string is formatted
//correctly
def bufStr = new ByteArrayOutputStream()
def oldStdOut = System.out;
def newStdOut = new PrintStream(bufStr)
System.out = newStdOut
objBeingTested.print()
System.out = oldStdOut
String prtTestStr = bufStr.toString()
assertTrue(Something-about-the-expected-output)
}

2 thoughts on “Redirecting stdOut in Groovy

Comments are closed.