views:

478

answers:

2

I'm writing integration tests using JUnit to automate the testing of a console based application. The application is homework but this part isn't the homework. I want to automate these tests to be more productive -- I don't want to have to go back and retest already tested parts of the application. (Standard reasons to use Unit tests)

Anyway, I can't figure out or find an article on capturing the output so that I can do assertEquals on it nor providing automated input. I don't care if the output/input goes to the console/output pane. I only need to have the test execute and verify the the output is what is expected given the input.

Anyone have an article or code to help out with this.

+4  A: 

Use System.setOut() (and System.setErr()) to redirect the output to an arbitrary printstream - which can be one that you read from programmatically.

For example:

final ByteArrayOutputStream myOut = new ByteArrayOutputStream();
System.setOut(new PrintStream(myOut));

// test stuff here...

final String standardOutput = myOut.toString();
Andrzej Doyle
So simply going `PrintStream _out = System.out;` Won't work?
Frank V
It would - i.e. you'd have a reference to the existing output stream - but you can't *read* anything from it as there are no appropriate methods to do so on the general `PrintStream` interface. The technique involves setting the output to a specific printstream you know how to read from.
Andrzej Doyle
+2  A: 

The System class has methods setIn(), setOut() and setErr() that allow you to set the standard input, output and error streams, e.g. to a ByteArrayOutputStream that you can inspect at will.

Michael Borgwardt