Skip to content

Instantly share code, notes, and snippets.

@schauder
Last active April 23, 2016 14:43
Show Gist options
  • Save schauder/7b3f0cf3649429e98f3dc9e2b3637010 to your computer and use it in GitHub Desktop.
Save schauder/7b3f0cf3649429e98f3dc9e2b3637010 to your computer and use it in GitHub Desktop.
A JUnit rule for testing output to `System.out`
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
public class SysoutRule implements TestRule {
private ByteOutputStream out;
public void contains(String string) {
assertThat(out, not(is((ByteOutputStream) null)));
assertThat(out.toString(), containsString(string));
}
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
final PrintStream oldOut = System.out;
out = new ByteOutputStream();
final PrintStream newOut = new PrintStream(out);
System.setOut(newOut);
try {
base.evaluate();
} finally {
System.setOut(oldOut);
newOut.close();
out = null;
}
}
};
}
}
@ancho
Copy link

ancho commented Apr 23, 2016

With ByteOutputStream you mean ByteArrayOutputStream?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment