5 September 2016

How to test method that uses System.out.print ?

Did you ever need to  System.out.println ?
 Quite unlikely? Well I am not surprised ,  because you never use it this kind of thing in production. However sometimes when you write some personal piece of software,you don't bother to use debugger or logging and you fancy to use System.out.println instead.

However as TDD fanatic you would love to test it but question is how ?
Well, it was something that I was curious about it and after doing wide search on internet and I found that in order to test it you need  set your own printstream, how see example below :).

public class Message {
    public static void error(String errorMessage) {
        System.err.print("ERROR: " + errorMessage);

public class MessageTest {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PrintStream original = System.err;

    public void setUp() throws Exception {
        System.setErr(new PrintStream(outputStream));

    public void tearDown() throws Exception {

    public void displayErrorTest() throws Exception {
        final String errorMessage = "Test";


        assertEquals("ERROR: " + errorMessage, outputStream.toString());


I hope this help