adam bien's blog

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.