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!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.