How to verify the Console output in JUnit Tests

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;

public void setStreams() {
    System.setOut(new PrintStream(out));
    System.setErr(new PrintStream(err));

public void restoreInitialStreams() {

And this is a sample Test class:

public void out() {
    System.out.print("test output");
    assertEquals("test output", out.toString());

public void err() {
    System.err.print("test output changed");
    assertEquals("test output", err.toString());