您的位置:軟件測試 > 開源軟件測試 > 開源單元測試工具 > junit
Junit測試時,如何截獲到Console的輸出
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時間:[ 2015/10/15 14:27:39 ] 推薦標簽:單元測試工具 軟件測試工具

  RT:
  參考如下Junit 測試代碼
  注釋部分
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.Assert.*;
public class HelloWorldTest {
PrintStream console = null;          // 聲明(為null):輸出流 (字符設(shè)備) console
ByteArrayOutputStream bytes = null;  // 聲明(為null):bytes 用于緩存console 重定向過來的字符流
HelloWorld hello;
@org.junit.Before
public void setUp() throws Exception {
hello = new HelloWorld();
bytes = new ByteArrayOutputStream();    // 分配空間
console = System.out;                   // 獲取System.out 輸出流的句柄
System.setOut(new PrintStream(bytes));  // 將原本輸出到控制臺Console的字符流 重定向 到 bytes
}
@org.junit.After
public void tearDown() throws Exception {
System.setOut(console);
}
@org.junit.Test
public void testResult() throws Exception {
hello.helloWorld();
String s = new String("Hello World! Hello Java! ");    // 注意:控制臺的換行,這里用 ' ' 表示
assertEquals(s, bytes.toString());          // bytes.toString() 作用是將 bytes內(nèi)容 轉(zhuǎn)換為字符流
}
}

軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd