Testing System.out.println Outputs

Although System.out.println invocations might be buried deep inside static methods:


public class App {

    public final static void main(String args[]) {
        if (args.length != 2) {
            usage();
            return;
        }
        //...
    }

    static void usage() {

        System.out.println("Use: java -jar airfield.App (...)");

    }
}

...they are actually very easy to test by mocking-out the PrintStream:


import java.io.PrintStream;
import org.junit.Test;
import static org.mockito.Matchers.startsWith;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class AppTest {

    @Test
    public void mainUsage() {
        PrintStream out = mock(PrintStream.class);
        System.setOut(out);
        App.main(new String[]{});
        verify(out).println(startsWith("Use:"));
    }
}

The example above was extracted from the: airfield and loadr projects.

See you at the Java 8 and Java EE 7 Testing andn Quality workshop at MUC Airport.


Web Apps, SPA, PWA with vanilla Java Script (ES 6+), CSS 3 and WebStandards only. As simple as possible, but not simpler. See you at: (Progressive) Web apps, Single Page Apps and WebStandards airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

You can also use PowerMock to test static methods.

Posted by Javin on October 18, 2015 at 05:16 AM CEST #

If the output is produced by multiple println's, you could also use the SystemOutRule.
http://stefanbirkner.github.io/system-rules/#SystemErrAndOutRule

Posted by Roland on October 19, 2015 at 12:09 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License