本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看<活动链接>
提问:用于System.out.println()的JUnit测试
我需要为设计欠佳的旧应用程序编写JUnit测试,并且正在向标准输出中写入许多错误消息。当getResponse(String request)方法正确运行时,它将返回XML响应:
@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并将某些内容写入标准输出。
有什么方法可以在JUnit中声明控制台输出吗?要捕获类似的情况:
System.out.println("match found: " + strExpr);
System.out.println("xml not well formed: " + e.getMessage());
复制代码
回答1:
使用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输出版本字符串等)
编辑: 该答案的先前版本System.setOut(null)在测试后被调用;这是NullPointerExceptions评论者引用的原因。
回答2:
有一个不错的库可以做到这一点:
来自文档的示例
public void MyTest {
@Rule
public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
@Test
public void overrideProperty() {
System.out.print("hello world");
assertEquals("hello world", systemOutRule.getLog());
}
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END






















![[桜井宁宁]COS和泉纱雾超可爱写真福利集-一一网](https://www.proyy.com/skycj/data/images/2020-12-13/4d3cf227a85d7e79f5d6b4efb6bde3e8.jpg)

![[桜井宁宁] 爆乳奶牛少女cos写真-一一网](https://www.proyy.com/skycj/data/images/2020-12-13/d40483e126fcf567894e89c65eaca655.jpg)