Presentation is loading. Please wait.

Presentation is loading. Please wait.

19-Aug-15 JUnit tests for output. Capturing output System.out.print and System.out.println usually “print” to the screen, but you can change that OutputStream.

Similar presentations


Presentation on theme: "19-Aug-15 JUnit tests for output. Capturing output System.out.print and System.out.println usually “print” to the screen, but you can change that OutputStream."— Presentation transcript:

1 19-Aug-15 JUnit tests for output

2 Capturing output System.out.print and System.out.println usually “print” to the screen, but you can change that OutputStream os = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(os); System.setOut(ps); If you do this, though, you probably want to change these methods back to “normal” when you are done PrintStream originalOut = System.out; (code from above) System.setOut(originalOut);

3 A class to test public class CaptureOutput { void myPrint(String message) { System.out.print(message); } void myPrintln(String message) { System.out.println(message); } }

4 JUnit framework import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintStream; import junit.framework.TestCase; public class CaptureOutputTest extends TestCase { CaptureOutput capture; protected void setUp() throws Exception { super.setUp(); capture = new CaptureOutput(); } // test methods go here }

5 Testing myPrint public final void testMyPrint() { // Prepare to capture output PrintStream originalOut = System.out; OutputStream os = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(os); System.setOut(ps); // Perform tests capture.myPrint("Hello, output!"); assertEquals("Hello, output!", os.toString()); // Restore normal operation System.setOut(originalOut); }

6 Testing myPrintln This does not work: capture.myPrintln("Hello, output!"); assertEquals("Hello, output!\n" + separator, os.toString()); Why not? Line separators are different on different systems! You need to add, not "\n", but the correct line separator! Here’s the correct code: String separator = System.getProperty("line.separator"); capture.myPrintln("Hello, output!"); assertEquals("Hello, output!" + separator, os.toString());

7 The End


Download ppt "19-Aug-15 JUnit tests for output. Capturing output System.out.print and System.out.println usually “print” to the screen, but you can change that OutputStream."

Similar presentations


Ads by Google