1. Overview

When unit testing we may occasionally want to test the messages that we write to standard output via System.out.println().

Although we’d generally prefer a logging framework over direct interaction with standard output, sometimes this isn’t possible.

In this quick tutorial, we’ll take a look at a couple of ways we can unit test System.out.println() using JUnit.

2. A Simple Print Method

Throughout this tutorial, the focus of our tests will be a simple method that writes to the standard output stream:

private void print(String output) {
    System.out.println(output);
}

A quick reminder that the out variable is a public static final PrintStream object which represents the standard output stream intended for system-wide usage.

3. Working With Core Java

Now let’s see how we can write a unit test to check the content of what we send to the println method. However, before we write our actual unit test, we’ll need to provide some initialization in our test:

private final PrintStream standardOut = System.out;
private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();

@BeforeEach
public void setUp() {
    System.setOut(new PrintStream(outputStreamCaptor));
}

In the setUp method, we reassign the standard output stream to a new PrintStream with a ByteArrayOutputStream. As we’re going to see this output stream is where the values will now be printed:

@Test
void givenSystemOutRedirection_whenInvokePrintln_thenOutputCaptorSuccess() {
    print("Hello Baeldung Readers!!");

    Assert.assertEquals("Hello Baeldung Readers!!", outputStreamCaptor.toString()
      .trim());
}

After we call the print method with the chosen text, we can then verify that the outputStreamCaptor contains the content we were expecting. We call the trim method to remove the new line that System.out.println() adds.

As the standard output stream is a shared static resource used by other parts of the system, we should take care of restoring it to its original state when our test terminates:

@BeforeEach
public void tearDown() {
    System.setOut(standardOut);
}

This ensures we don’t get any unwanted side effects later on in other tests.

#java #testing #junit #developer

Unit Testing of System.out.println() with JUnit
101.85 GEEK