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 :).

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

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


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

    @After
    public void tearDown() throws Exception {
        System.setErr(original);
    }

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

        //When
        Message.error(errorMessage);

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

    }
}

I hope this help

No comments:

Post a Comment