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

  RT:
  參考如下Junit 測(cè)試代碼
  注釋部分
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 重定向過(guò)來(lái)的字符流
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));  // 將原本輸出到控制臺(tái)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! ");    // 注意:控制臺(tái)的換行,這里用 ' ' 表示
assertEquals(s, bytes.toString());          // bytes.toString() 作用是將 bytes內(nèi)容 轉(zhuǎn)換為字符流
}
}

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