JUnit tests for output Capturing output n System

  • Slides: 7
Download presentation
JUnit tests for output

JUnit tests for output

Capturing output n System. out. print and System. out. println usually “print” to the

Capturing output n System. out. print and System. out. println usually “print” to the screen, but you can change that n n Output. Stream os = new Byte. Array. Output. Stream(); Print. Stream ps = new Print. Stream(os); System. set. Out(ps); If you do this, though, you probably want to change these methods back to “normal” when you are done n Print. Stream original. Out = System. out; (code from above) System. set. Out(original. Out);

A class to test n public class Capture. Output { void my. Print(String message)

A class to test n public class Capture. Output { void my. Print(String message) { System. out. print(message); } void my. Println(String message) { System. out. println(message); } }

JUnit framework n import java. io. Byte. Array. Output. Stream; import java. io. Print.

JUnit framework n import java. io. Byte. Array. Output. Stream; import java. io. Print. Stream; import junit. framework. Test. Case; public class Capture. Output. Test extends Test. Case { Capture. Output capture; protected void set. Up() throws Exception { super. set. Up(); capture = new Capture. Output(); } // test methods go here }

Testing my. Print n public final void test. My. Print() { // Prepare to

Testing my. Print n public final void test. My. Print() { // Prepare to capture output Print. Stream original. Out = System. out; Output. Stream os = new Byte. Array. Output. Stream(); Print. Stream ps = new Print. Stream(os); System. set. Out(ps); // Perform tests capture. my. Print("Hello, output!"); assert. Equals("Hello, output!", os. to. String()); // Restore normal operation System. set. Out(original. Out); }

Testing my. Println n This does not work: n n Why not? n n

Testing my. Println n This does not work: n n Why not? n n n capture. my. Println("Hello, output!"); assert. Equals("Hello, output!n" + separator, os. to. String()); Line separators are different on different systems! You need to add, not "n", but the correct line separator! Here’s the correct code: n String separator = System. get. Property("line. separator"); capture. my. Println("Hello, output!"); assert. Equals("Hello, output!" + separator, os. to. String());

The End

The End