dumpall icon indicating copy to clipboard operation
dumpall copied to clipboard

Add ConsoleCaptor

Open Hakky54 opened this issue 1 year ago • 0 comments

This pull request is similar to this one: https://github.com/Vedenin/useful-java-links/pull/131

LogCaptor is focussed on capturing data from a Logger (Java Util Logging, SLF4J, Log4J2) which includes log level based messages, excpetions, unformatted and formatted logs etc. While ConsoleCaptor will just capture everything which is printed to the console either by using System.out or Logger output to the console.

ConsoleCaptor is designed to easily capture everything from the console output for assertions. It takes away the verbose setup of preparing everything and also properly closing the streams and reverting the temporally configuration under the covers. The end-user may have something similar to this setup:

public class FooService {

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

}

With the accompanied unit test with usage of ConsoleCaptor:

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();
    }
}

Hakky54 avatar Jan 11 '23 10:01 Hakky54