Last active
April 23, 2016 14:43
-
-
Save schauder/7b3f0cf3649429e98f3dc9e2b3637010 to your computer and use it in GitHub Desktop.
A JUnit rule for testing output to `System.out`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With ByteOutputStream you mean ByteArrayOutputStream?