待測類(CreateString)如下:
public class CreateString {
public void createString() {
//Output the following string "1 2 3"
System.out.print("1 2 3\n");
//Output the following string "1 2 3"
System.out.print("1 "+"2 "+"3\n");
//Output the following string "1 2 3"
System.out.print(new String("1 2 3\n"));
//Output the following string "1 2 3"
System.out.print(new String("1 2 3\n"));
}
}
開始編寫測試類(CreateStringTest)如下:
-
在CreateString.Java 文件上右鍵(或Ctrl+N),彈出下圖:
-
選擇 JUnit test case 或者 Test Suite,彈出下圖:
-
編寫如下測試類代碼
import static org.junit.Assert.*; // Junit 提供斷言 assert
import java.io.ByteArrayOutputStream; // 輸出緩沖區
import java.io.PrintStream; // 打印輸出流
import org.junit.Test; // 提供測試public class CreateStringTest {
// 做三件事情:定義打印輸出流(PrintStream console)、輸出字節流數組 bytes、新建一個待測對象createString
PrintStream console = null;
ByteArrayOutputStream bytes = null;
CreateString createString;@org.junit.Before // 預處理 public void setUp() throws Exception { createString = new CreateString(); bytes = new ByteArrayOutputStream(); console = System.out; System.setOut(new PrintStream(bytes)); } @org.junit.After // 后處理 public void tearDown() throws Exception { System.setOut(console); } @org.junit.Test // 測試 public void testResult() throws Exception { createString.createString(); // 調用方法createString() 輸出一系列字符串到 (輸出字節流數組)bytes String s = new String("1 2 3\n"+"1 2 3\n"+"1 2 3\n"+"1 2 3\n"); // 作為 Oracle assertEquals(s, bytes.toString()); // 比較 Oracle 和 實際輸出的值 bytes, PS 需要將數組對象 bytes 轉換為字符串。 }
}