Download presentation
Presentation is loading. Please wait.
Published byMyra Chase Modified over 9 years ago
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.