Testing Console Output using JUnit in Java

Reading Time: 2 minutes

Sometimes you might need to test a method which does not return anything but only prints the output on console. For example, if you are writing your own version of print or format methods. Your test cases should be needing to check whether the output is printed correctly on the console.

Without a return value it gets difficult to test the veracity of the test. However, there is a way you can achieve. The idea is basically to change the System’s default output stream to a managed stream, and then verify whether the method as correct output. See the code below.

create a replacement stream. If you want to separate error output, one stream for that as well.

private final ByteArrayOutputStream outstream = new ByteArrayOutputStream();
private final ByteArrayOutputStream errstream = new ByteArrayOutputStream();

Store the original streams so that you can restore them later.

private final PrintStream out = System.out;
private final PrintStream err = System.err;

Replace the original output and error streams in in setup / @Before annotated method.

@Before
public void setUp() {
    System.setOut(new PrintStream(outstream));
    System.setErr(new PrintStream(errstream));
}

Reset to original output and error streams in teardown / @After annotated method.

@After
public void tearDown() {
    System.setOut(out);
    System.setErr(err);
}

Write your test case. Call the method that is supposed to print on console. Collect the output from the managed stream and compare it with expected output.

@Test
public void test() {

    methodThatPrintsHelloToConsole();
    String actual = outstream.toString();

    StringBuilder sb = new StringBuilder();
    sb.append("hello");
    String expected = sb.toString();

    assertEquals(expected, actual);
}

And that is it. Oh wait. There is a small catch. If you are using a windows system, your console will output CRLF instead of LF for new lines. So this above test will fail. To fix this, you need to replace all CRLFs with normal LFs.

actual = actual.replaceAll("\\r\\n", "\n");
actual = actual.replaceAll("\\r", "\n");

Voila !

1 thought on “Testing Console Output using JUnit in Java”

  1. Pingback: canadianpharmaceuticalsonline.home.blog

Leave a Reply