Adam Bien's Weblog

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.


NEW workshop: HTML 5 and JavaScript Essentials, Three days in April 2017: from Java EE 7 Architectures over Microservices to Performance, Troubleshooting and Monitoring
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacks.news

A book about rethinking Java EE Patterns

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
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License