JUnit with System.out.println

System.out.println and System.out.print will usually print the output String to the screen, however with the below code, you could actually redirect the print out to a Stream and thereafter use it for JUnit testing.

//Prepare to redirect output
OutputStream os = new ByteArrayOutStream();
PrintStream ps = new PrintStream(os);
System.setOut(ps);

System.out.print(“Hello World”);
assertEquals(“Hello World”, os.toString());

System.out.println(“Hello World”);
//if you decided to do a println instead, do note that you would need System.getProperty(“line.separator”) to properly test for the next line
assertEquals(“Hello World” + System.getProperty(“line.separator”), os.toString());

//Restore normal output
PrintStream originalOut = System.out;
System.setOut(originalOut);

Advertisements
This entry was posted in Java and tagged , . Bookmark the permalink.

One Response to JUnit with System.out.println

  1. public void WhateverImTesting() throws Exception {

    //Prepare to redirect output
    OutputStream os = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(os);
    System.setOut(ps);

    System.out.print(“Hello World”);
    assertEquals(“Hello World”, os.toString());

    System.out.println(“Hello World”);
    //if you decided to do a println instead, do note that you would need System.getProperty(“line.separator”) to properly test for the next line
    //assertEquals(“Hello World” + System.getProperty(“line.separator”), os.toString());

    //Restore normal output
    PrintStream originalOut = System.out;
    System.setOut(originalOut);

    }

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s