🎯 ConsoleCaptor captures console output for unit testing purposes

Overview

Actions Status Quality Gate Status Coverage Reliability Rating Security Rating Vulnerabilities Apache2 license Maven Central javadoc FOSSA Status Join the chat at https://gitter.im/hakky54/consolecaptor

SonarCloud

ConsoleCaptor

Install library with:

Install with maven

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

Install with Gradle

testImplementation 'io.github.hakky54:consolecaptor:1.0.2'

Install with Scala SBT

libraryDependencies += "io.github.hakky54" % "consolecaptor" % "1.0.2" % Test

Install with Apache Ivy

<dependency org="io.github.hakky54" name="consolecaptor" rev="1.0.2" />

Table of contents

  1. Introduction
  2. Usage
  3. Contributing
  4. License

Introduction

Hey, hello there 👋 Welcome, you are visitors I hope you will like this library ❤️

ConsoleCaptor is a library which will enable you to easily capture the output of the console for unit testing purposes.

Do you want to capture logs? Please have a look at LogCaptor.

Advantages

  • No mocking required
  • No custom JUnit extension required
  • Plug & play
  • Zero transitive dependencies

Tested Java versions

  • Java 8
  • Java 11+

See the unit test ConsoleCaptorShould for all the scenario's.

Usage

Capture console output
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:
import static org.assertj.core.api.Assertions.assertThat;

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

public class FooServiceShould {

    @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();
    }
}
Initialize ConsoleCaptor once and reuse it during multiple tests with clearOutput() method within the afterEach method:
import nl.altindag.console.ConsoleCaptor;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;

public class FooServiceShould {

    private static ConsoleCaptor consoleCaptor;
    
    @BeforeAll
    public static setupConsoleCaptor() {
        consoleCaptor = new ConsoleCaptor();
    }

    @AfterEach
    public void clearOutput() {
        consoleCaptor.clearOutput();
    }
    
    @AfterAll
    public static void tearDown() {
        consoleCaptor.close();
    }

    @Test
    public void captureStandardOutput() {
        FooService service = new FooService();
        service.sayHello();

        assertThat(consoleCaptor.getStandardOutput()).contains("Keyboard not responding. Press any key to continue...");
    }

    @Test
    public void captureErrorOutput() {
        FooService service = new FooService();
        service.sayHello();

        assertThat(consoleCaptor.getErrorOutput()).contains("Congratulations, you are pregnant!");
    }

}

Contributing

There are plenty of ways to contribute to this project:

  • Give it a star
  • Join the Gitter room and leave a feedback or help with answering users questions
  • Submit a PR

License

FOSSA Status

You might also like...

Don't use this maliciously, this is for testing

log4j-exploit-example Don't use this maliciously, this is for testing Specifically for testing within Minecraft, but this will probably work on other

Dec 25, 2021

Sniffy - interactive profiler, testing and chaos engineering tool for Java

Sniffy - interactive profiler, testing and chaos engineering tool for Java

Sniffy Sniffy is a Java profiler which shows the results directly in your browser. It also brings profiling to your unit (or rather component) tests a

Dec 23, 2022

QuickPerf is a testing library for Java to quickly evaluate and improve some performance-related properties

QuickPerf is a testing library for Java to quickly evaluate and improve some performance-related properties

QuickPerf is a testing library for Java to quickly evaluate and improve some performance-related properties quickperf.io 📙 Documentation Annotations

Dec 15, 2022

A collection of JUnit rules for testing code which uses java.lang.System.

System Rules System Rules is a collection of JUnit rules for testing code which uses java.lang.System. System Lambda is an alternative to System Rules

Dec 22, 2022

Practice and testing with Java 11, Prometheus, and Spring-boot with MicroService Architecture. Designed to run on Kubernetes in minikube.

Practice and testing with Java 11, Prometheus, and Spring-boot with MicroService Architecture. Designed to run on Kubernetes in minikube.

This application was written by Andrew Aslakson Built to run on minikube using kubernetes General race tracking system? Secure with Firebase Authentic

Feb 5, 2022

🏫 Testing Workshop for Factoria F5 Bootcamp

ms-test--factoriaf5-testing 🏫 Testing Workshop for Factoria F5 Sample used in Adevinta Spain's Factoria F5 masterclasses Develop Clone/fork this repo

Mar 2, 2022

F5 BIG-IP iControl REST vulnerability RCE exploit with Java including a testing LAB

F5 BIG-IP iControl REST vulnerability RCE exploit with Java including a testing LAB

CVE-2022-1388 F5 BIG-IP iControl REST vulnerability RCE exploit with Java and ELF. Included Scan a single target Scan many targets Exploit with a shel

Sep 24, 2022

The code examples of the "Effective Software Testing: A Developer's Guide" book

Effective software testing This repository contains the code examples of the Software Testing: A Developer's Guide book, by Maurício Aniche. Each fold

Dec 29, 2022

Captures log entries for unit testing purposes

LogCaptor Install with maven dependency groupIdio.github.hakky54/groupId artifactIdlogcaptor/artifactId version2.4.0/version

Jan 1, 2023

Jansi is a small java library that allows you to use ANSI escape sequences to format your console output which works even on windows.

Description Jansi is a small java library that allows you to use ANSI escape codes to format your console output which works even on Windows. It also

Dec 28, 2022

JVM Profiler Sending Metrics to Kafka, Console Output or Custom Reporter

Uber JVM Profiler Uber JVM Profiler provides a Java Agent to collect various metrics and stacktraces for Hadoop/Spark JVM processes in a distributed w

Dec 22, 2022

GreenMail is an open source, intuitive and easy-to-use test suite of email servers for testing purposes.

GreenMail GreenMail is an open source, intuitive and easy-to-use test suite of email servers for testing purposes. Supports SMTP, POP3, IMAP with SSL

Dec 28, 2022

Development Driven Testing (DDT) lets you generate unit tests from a running application. Reproduce a bug, generate a properly mocked test

DDTJ: It kills bugs DDT is the flip side of TDD (Test-driven development). It stands for "Development Driven Tests". Notice that it doesn’t contradict

Dec 30, 2021

Java Concolic Unit Testing Engine

jCUTE The Java Concolic Unit Testing Engine (jCUTE) automatically generates unit tests for Java programs. Concolic execution combines randomized concr

Nov 7, 2022

A unit testing library for varying test data.

Burst A unit testing library for varying test data. DEPRECATED: Burst remains stable and functional, but you should check out TestParameterInjector fr

Oct 9, 2022

Write JSON unit tests in less code. Great for testing REST interfaces.

JSONassert Write JSON unit tests in less code. Great for testing REST interfaces. Summary Write JSON tests as if you are comparing a string. Under the

Dec 29, 2022

How to configure Replica Set with Embedded Mongo using Spring Boot and Flapdoodle for unit testing code that uses mongodb transactions

Spring Boot Embedded Mongo with Replica Set This project defines a basic rest service that allows users to update records of a Person (name and email)

Nov 1, 2022

Spring REST API for financial management, developed with Java 11, JWT for authentication, JUnit for unit testing and Oracle Database

Spring REST API for financial management, developed with Java 11, JWT for authentication, JUnit for unit testing and Oracle Database

control_financial Spring REST API for financial management, developed with Java 11, JWT for authentication, JUnit for unit testing and Oracle Database

May 27, 2022

FizzBuzz Enterprise Edition is a no-nonsense implementation of FizzBuzz made by serious businessmen for serious business purposes.

FizzBuzzEnterpriseEdition Enterprise software marks a special high-grade class of software that makes careful use of relevant software architecture de

Dec 31, 2022
Comments
  • ConsoleCaptor#clearOutput doesn't reset System.out and System.err

    ConsoleCaptor#clearOutput doesn't reset System.out and System.err

    Describe the bug The method ConsoleCaptor#clearOutput creates new streams but doesn't register them to System.out and System.err. So subsequent calls to #getStandardOutput() and #getErrorOutput() always return empty lists.

    To Reproduce

    try (ConsoleCaptor console = new ConsoleCaptor()) {
        System.out.println("hello");
        // ok
        assertThat(console.getStandardOutput()).containsExactly("hello");
    
        console.clearOutput();
    
        System.out.println("world");
        // ko
        assertThat(console.getStandardOutput()).containsExactly("world");
    }
    
    opened by charphi 3
  • getStandardOutput() not returning anything

    getStandardOutput() not returning anything

    Hello,

    I am trying to use ConsoleCaptor to get logs from the console. I tried using LogCaptor, but it doesn't seem to work with my Maven repositories, so I resorted to ConsoleCaptor since it seems quick and easy to set up!

    Background I have a class that uses SL4J logging binded to a Log4J2 configuration. I have set up my log4j2.xml file with a Console Appender that logs error messages to the console. I know this works, because when I run the unit tests, I can see the log message printed in the console. I think the issue I am experiencing is ConsoleCaptor not picking up the log message from the console, because when I do a System.out.println(consoleCaptor.getStandardOutput()), nothing is returned.

    My pom.xml file has the following dependencies:

    <dependencies>
            <dependency>
                <groupId>io.github.hakky54</groupId>
                <artifactId>consolecaptor</artifactId>
                <version>1.0.2</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-core</artifactId>
            </dependency>
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-slf4j18-impl</artifactId>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>2.0.0-alpha7</version>
            </dependency>
    

    In my test file, I have set up ConsoleCaptor as follows:

    @BeforeAll
        public static void setupConsoleCaptor() {
            consoleCaptor = new ConsoleCaptor();
        }
    
        @AfterEach
        public void clearOutput() {
            consoleCaptor.clearOutput();
        }
    
        @AfterAll
        public static void tearDown() {
            consoleCaptor.close();
        }
    

    Do you have any idea what I might be missing or doing wrong?

    no-activity 
    opened by tiannahomer 2
Owner
Hakan Altındağ
Hakan Altındağ is a freelance Java and Search Engineer
Hakan Altındağ
A unit testing library for varying test data.

Burst A unit testing library for varying test data. DEPRECATED: Burst remains stable and functional, but you should check out TestParameterInjector fr

Square 464 Oct 9, 2022
How to configure Replica Set with Embedded Mongo using Spring Boot and Flapdoodle for unit testing code that uses mongodb transactions

Spring Boot Embedded Mongo with Replica Set This project defines a basic rest service that allows users to update records of a Person (name and email)

Divyansh Shekhar Gaur 4 Nov 1, 2022
Spring REST API for financial management, developed with Java 11, JWT for authentication, JUnit for unit testing and Oracle Database

control_financial Spring REST API for financial management, developed with Java 11, JWT for authentication, JUnit for unit testing and Oracle Database

Vinicius Cassaro 1 May 27, 2022
Spring Boot Rest API unit test with Junit 5, Mockito, Maven

Spring Boot Rest API unit testing with Junit 5, Mockito, Maven Apply Spring Boot @WebMvcTest for Rest Controller Unit Test with JUnit 5 and Mockito. F

null 19 Dec 22, 2022
Unit 1 for WASP composable software tools project

one This unit uses Spoon to find program constructs from a Java source file, based on their visibility. It currently supports public and private class

Deepika Tiwari 2 Oct 13, 2021
Auto-Unit-Test-Case-Generator automatically generates high-level code-coverage JUnit test suites for Java, widely used within the ANT Group.

中文README传送门 What is Auto-Unit-Test-Case-Generator Auto-Unit-Test-Case-Generator generates JUnit test suites for Java class just as its name. During te

TRaaS 108 Dec 22, 2022
GodType is a very simple Bukkit plugin to allow the console (or a player) to chat as a defined name.

GodType GodType is a very simple Bukkit plugin to allow the console (or a player) to chat as a defined name. Config A config.yml file will be created

null 1 Dec 24, 2021
A plugin that serving completely in-game webview based console backend for grasscutter

MojoConsolePlus EN|中文 MojoConsolePlus(MCP) is a Grasscutter plugin (Apart from 4Benj's GCGM plugin) and it's goal is to implement fully in-game webwie

null 68 Dec 13, 2022
A Text Based, Turn-Based, Strategy Game to be played in console

ConsoleGame A Text Based, Turn-Based, Strategy Game to be played in console. Feel free to fix any retardation in my code (meaning bugs, stupid/spaghet

Bertrahm 2 Jul 17, 2022
Simple Design for Java bridge with Javascript. Also can get javascript console.log.

SDBridgeKotlin is here. If your h5 partner confused about how to deal with iOS and Android. This Demo maybe help. 最常见的问题. WebViewJavascriptBridge is n

null 25 Dec 18, 2022