JUnit 測試時,如何截獲 Console 的輸出

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.junit.Assert.*;

public class HelloWorldTest  {
	PrintStream console = null; // 聲明(爲null):輸出流 (字符設備) 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!\n"); // 注意:控制檯的換行,這裏用
																// '\n' 表示
		assertEquals(s, bytes.toString()); // bytes.toString() 做用是將 bytes內容
											// 轉換爲字符流
	}
}
相關文章
相關標籤/搜索