This tutorial shows how to assert the Console output of a JUnit Test:
First of all we need a class which sets the out and err streams to the PrintStream in the @Before and @After callback methods:
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
private final ByteArrayOutputStream err = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;
@Before
public void setStreams() {
System.setOut(new PrintStream(out));
System.setErr(new PrintStream(err));
}
@After
public void restoreInitialStreams() {
System.setOut(originalOut);
System.setErr(originalErr);
}
And this is a sample Test class:
@Test
public void out() {
System.out.print("test output");
assertEquals("test output", out.toString());
}
@Test
public void err() {
System.err.print("test output changed");
assertEquals("test output", err.toString());
}