我需要为设计欠佳的旧应用程序编写JUnit测试,并且正在向标准输出中写入许多错误消息。当getResponse(String request)方法正确运行时,它将返回XML响应:
getResponse(String request)
@BeforeClass public static void setUpClass() throws Exception { Properties queries = loadPropertiesFile("requests.properties"); Properties responses = loadPropertiesFile("responses.properties"); instance = new ResponseGenerator(queries, responses); } @Test public void testGetResponse() { String request = "<some>request</some>"; String expResult = "<some>response</some>"; String result = instance.getResponse(request); assertEquals(expResult, result); }
但是,当XML格式错误或无法理解请求时,它将返回null并将某些内容写入标准输出。
null
有什么方法可以在JUnit中声明控制台输出?要捕获类似的情况:
System.out.println("match found: " + strExpr); System.out.println("xml not well formed: " + e.getMessage());
使用ByteArrayOutputStream和System.setXXX很简单:
ByteArrayOutputStream
System.setXXX
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); private final PrintStream originalOut = System.out; private final PrintStream originalErr = System.err; @Before public void setUpStreams() { System.setOut(new PrintStream(outContent)); System.setErr(new PrintStream(errContent)); } @After public void restoreStreams() { System.setOut(originalOut); System.setErr(originalErr); }
样本测试案例:
@Test public void out() { System.out.print("hello"); assertEquals("hello", outContent.toString()); } @Test public void err() { System.err.print("hello again"); assertEquals("hello again", errContent.toString()); }
我使用此代码测试了命令行选项(断言-version输出版本字符串等)