Testing System.out.println() with JUnit
How can you write JUnit tests for an application that writes error messages to standard output, especially when these messages are inconsistent and unreliable? To test these scenarios effectively, you must capture the console output and assert its content.
Redirect Console Output
Capturing console output requires redirecting both standard output (System.out) and standard error (System.err) during the test. This can be achieved using ByteArrayOutputStream and System.setXXX methods. Here's an example implementation:
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); private final PrintStream originalOut = System.out; private final PrintStream originalErr = System.err; @Before public void setUpStreams() { System.setOut(new PrintStream(outContent)); System.setErr(new PrintStream(errContent)); } @After public void restoreStreams() { System.setOut(originalOut); System.setErr(originalErr); }
Sample Test Cases
With the console output redirected, you can write test cases to assert the expected output:
@Test public void out() { System.out.print("hello"); assertEquals("hello", outContent.toString()); } @Test public void err() { System.err.print("hello again"); assertEquals("hello again", errContent.toString()); }
These test cases assert that the system output is as expected, allowing you to validate if the application logs are consistent with different request responses.
Note: In earlier versions of this answer, System.setOut(null) was used after the tests, which could lead to NullPointerExceptions. The updated code correctly restores the original streams after each test to avoid such issues.
The above is the detailed content of How to Unit Test `System.out.println()` in JUnit?. For more information, please follow other related articles on the PHP Chinese website!