JUnit tests for printing

Download Report

Transcript JUnit tests for printing

JUnit tests for output
26-Jul-16
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);
A class to test

public class CaptureOutput {
void myPrint(String message) {
System.out.print(message);
}
void myPrintln(String message) {
System.out.println(message);
}
}
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
}
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);
}
Testing myPrintln

This does not work:


Why not?



capture.myPrintln("Hello, output!");
assertEquals("Hello, output!\n" + separator, os.toString());
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());
The End