问题描述
我需要为一个设计不良的旧应用程序编写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或不理解请求时,返回<$
But when it gets malformed XML or does not understand the request it returns null
and writes some stuff to standard output.
有没有办法在JUnit中声明控制台输出?c $ c> null 捕获如下情况:
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());
推荐答案
使用和System.setXXX很简单:
using ByteArrayOutputStream and System.setXXX is simple:
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
@After
public void cleanUpStreams() {
System.setOut(null);
System.setErr(null);
}
样本测试用例:
@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());
}
我使用这个代码来测试命令行选项版本字符串等)
I used this code to test the command line option (asserting that -version outputs the version string, etc etc)
这篇关于System.out.println()的JUnit测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!