System.out.println() 的 JUnit 测试 [英] JUnit test for System.out.println()
问题描述
我需要为一个旧的应用程序编写 JUnit 测试,该应用程序设计不佳并且向标准输出写入了大量错误消息.当 getResponse(String request)
方法正确运行时,它会返回一个 XML 响应:
I need to write JUnit tests for an old application that's poorly designed and is writing a lot of error messages to standard output. When the getResponse(String request)
method behaves correctly it returns a XML response:
@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
并将一些内容写入标准输出.
But when it gets malformed XML or does not understand the request it returns null
and writes some stuff to standard output.
有没有办法在 JUnit 中断言控制台输出?捕捉以下情况:
Is there any way to assert console output in JUnit? To catch cases like:
System.out.println("match found: " + strExpr);
System.out.println("xml not well formed: " + e.getMessage());
推荐答案
using ByteArrayOutputStream 和 System.setXXX 很简单:
using ByteArrayOutputStream and System.setXXX is simple:
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 输出版本字符串等)
I used this code to test the command line option (asserting that -version outputs the version string, etc etc)
测试后,此答案的先前版本称为 System.setOut(null)
;这是NullPointerExceptions评论者引用的原因.
Prior versions of this answer called System.setOut(null)
after the tests; This is the cause of NullPointerExceptions commenters refer to.
这篇关于System.out.println() 的 JUnit 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!