DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Testing Asynchronous Systems, Part 4: A Technique-by-Level Test Strategy
  • Same Prompt, Different Test: Using AI Agent Workspaces to Make Testing Repeatable
  • Testing Business Programs Without Constructing Domain Objects
  • Why Standard Test Automation Misses the Failures That Matter in AI Agent Systems

Trending

  • Build Production-Ready AI Phone Agents: Infrastructure, Models, and Telephony
  • Why Your RAG Pipeline, Not Your LLM, Is Causing Hallucinations
  • Your Cloud Infrastructure Is Elastic, and So Should Be Your Cost Governance
  • Hosted Code Interpreter in Spring AI: Letting OpenAI Write and Run Python via the Responses API

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Unit Testing Console Output Made Easy

Unit Testing Console Output Made Easy

Unit testing presents specific challenges around logging. A developer and DZone Core members discuss an open-source project he created to help.

By 
Hakan Altındağ
·
Jul. 16, 21 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
12.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Introduction

Testing the console output, why even bother? Some developers don't care and some do care. I think any test which asserts some output based on the same action for your target class is useful as it validates the behavior of your service when it is called. Your target class or some other class under the covers may generate logs or any kind of output on the console which you want to capture to assert it. Testing these kinds of cases will give you more confidence that your application is working as expected.

Capturing the console output and using that to assert isn't that hard in plain java. It is actually very easy but verbose. Most of the time I ended up creating a utility class which I copied to different projects. I had to maintain different versions which was not so fun at all. So I decided to generate a library out of it and contribute back to the community to give them also the possibility of capturing the console output without introducing verbose code.

Install the Library

Include the following dependency in your project as a test dependency:

XML
 
<dependency>
    <groupId>io.github.hakky54</groupId>
    <artifactId>consolecaptor</artifactId>
    <version>1.0.0</version>
    <scope>test</scope>
</dependency>

Or get here the latest version: Maven Central

View the source code here: GitHub - ConsoleCaptor

Target Service Class

Let's assume you have the following service which creates output on the console:

Java
 
public class FooService {

    public void sayHello() {
        System.out.println("Keyboard not responding. Press any key to continue...");
        System.err.println("Congratulations, you are pregnant!");
    }

}

Unit Test

Let's create a unit test for this service to assert the generated messages on the console:

Java
 
import static org.assertj.core.api.Assertions.assertThat;

import nl.altindag.console.ConsoleCaptor;
import org.junit.jupiter.api.Test;

public class FooServiceTest {

    @Test
    public void captureStandardAndErrorOutput() {
        ConsoleCaptor consoleCaptor = new ConsoleCaptor();

        FooService fooService = new FooService();
        fooService.sayHello();

        assertThat(consoleCaptor.getStandardOutput()).contains("Keyboard not responding. Press any key to continue...");
        assertThat(consoleCaptor.getErrorOutput()).contains("Congratulations, you are pregnant!");
        
        consoleCaptor.close();
    }
}

Testing Logs From Loggers

ConsoleCaptor is able to capture anything which is printed on the console even logs from logging API such as SLF4J, Log4J2, Log4J, Java Util Logging. It will return just the raw text including the log level, timestamp, etc. If you require to do more advanced logging assertions I can recommend LogCaptor, which is also capable of capturing an exception that is being logged by the logging API or the MDC (managed diagnostic context) information. Please have a look here: LogCaptor - Unit Testing Log Messages Made Easy.

unit test Console (video game CLI)

Published at DZone with permission of Hakan Altındağ. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Testing Asynchronous Systems, Part 4: A Technique-by-Level Test Strategy
  • Same Prompt, Different Test: Using AI Agent Workspaces to Make Testing Repeatable
  • Testing Business Programs Without Constructing Domain Objects
  • Why Standard Test Automation Misses the Failures That Matter in AI Agent Systems

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook