NOTES INDEX This page is part of the collection of "notes" - these can be considered to be micro-blogs.
Java/Kotlin Unit Testing – Test Stdout/Stderr/Logs

Java/Kotlin Unit Testing – Test Stdout/Stderr/Logs

Note: see also my old blog post if you want a more complex solution 😉 It targets at replacing the log appender. The below described method is simpler (nice!), it just listens in on ALL standard output+errors.

When using spring-boot unit testing (library spring-boot-test-2.6.2.jar or newer), you can capture the output as send to the standard out and standard error channels. This allows for example testing output to log statements (by sending logs to stdout / console appender).

From the JavaDocs:

package org.springframework.boot.test.system;

// JUnit Jupiter @Extension to capture System.out and System.err. Can be registered for an entire
// test class or for an individual test method via @ExtendWith. This extension provides parameter
// resolution for a CapturedOutput instance which can be used to assert that the correct output
// was written.
// To use with @ExtendWith, inject the CapturedOutput as an argument to your test class
// constructor, test method, or lifecycle methods:

class MyTest {

       void test(CapturedOutput output) {

       void after(CapturedOutput output) {

A Kotlin example:

import org.springframework.boot.test.system.OutputCaptureExtension
import org.hamcrest.CoreMatchers.containsString

class SomeTest {

    fun `the test method`(output: CapturedOutput) {

        // ... do something here which logs info ...

        // and check expected output
        assertThat(output.all, containsString("expected output"))

Ok, stop reading here if you can use above examples 😉

I was curious as to HOW spring does this capturing, and you can simplify their implementation with bare minimal functionality to something like this (if you are not using spring for example):

Java example:

        // Attach a buffer to stdout
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        PrintStream originalStdout = System.out; // same possible for System.err
        System.setOut(new PrintStream(buffer)); // same possible for System.setErr()

        // --------------------------------------------------------------------------------
        // Test sending data (note: it does not echo to stdout, it is going to our buffer)
        // This can also be done by a log-appender sending it to stdout / console
        // --------------------------------------------------------------------------------

        // Restore to normal stdout channel

        // Do something with captured data
        System.out.println("Captured: " + buffer.toString());

That’s all there is to it 😉 Just alter the Std-Out to a buffer, and back at the end.

Or you can try a more complex example, which DOES echo the data to the console while also putting it in a buffer:

import lombok.SneakyThrows;

public class Test {

    // This main us used in this example instead of a normal test class.
    public static void main(String[] args) {
        CaptureStdOutAndStderr capture = new CaptureStdOutAndStderr();


        // Restore normal output

        System.out.println("captured:\n" + capture.getOutput());

    public static class CaptureStdOutAndStderr extends PrintStream {
        private static PrintStream parentStdout = null;
        private static PrintStream parentStdErr = null;
        private static final ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        public String getOutput() {
            return buffer.toString();

        public boolean contains(String search) {
            return buffer.toString().contains(search);

        public CaptureStdOutAndStderr() {
            if (parentStdout == null) {
                parentStdout = System.out;
                parentStdErr = System.err;

        public void close() {
            if (parentStdout != null) {
                parentStdout = null;
                parentStdErr = null;

        public void write(int b) {
            write(new byte[] { (byte) (b & 0xFF) });

        public void write(byte[] b, int off, int len) {
            buffer.write(b, off, len);
            parentStdout.write(b, off, len);

        public void flush() {

Note: this is just a hacky example to explain what sort of things you could try, nothing really serious. This would need some refactoring / cleaning. It has a nasty mix between static and non-static, no error handling, and puts std-out and std-err on one big pile.

February 3, 2022

Leave a Reply

Your email address will not be published.