JUnit Testing for System.out.println() Output
In legacy applications, troubleshooting can be challenging when relying solely on standard error messages printed to the console. To mitigate this, JUnit provides methods for capturing and asserting console output.
To test System.out.println() output, consider the following approach:
Initialize Output Capture:
Execute Tests:
Assert Output:
Example Test Cases:
@Test public void testOut() { System.out.print("hello"); assertEquals("hello", outContent.toString()); } @Test public void testErr() { System.err.print("error occurred"); assertEquals("error occurred", errContent.toString()); }
Note: Ensure System.setOut() and System.setErr() calls are reverted after each test using originalOut and originalErr. Failure to do so can lead to NullPointerExceptions during subsequent tests.
The above is the detailed content of How Can JUnit Effectively Test `System.out.println()` Output?. For more information, please follow other related articles on the PHP Chinese website!