Testing System Output in JUnit
In legacy systems, applications may print error messages or debug information to the standard output instead of returning errors explicitly. Testing such output can be challenging with JUnit.
Problem:
Unit tests need a way to assert the content of the console output to catch cases where System.out.println() is used instead of proper error handling.
Solution:
Using ByteArrayOutputStream and System.setXXX() allows us to redirect the system output and capture it for testing.
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); }
Test Cases:
@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()); }
Note:
Prior versions of this answer called System.setOut(null) after the tests. This is the cause of NullPointerExceptions commenters referred to.
The above is the detailed content of How to Test System.out and System.err Output in JUnit?. For more information, please follow other related articles on the PHP Chinese website!