测试写入 Java OutputStream 的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/225073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Testing what's written to a Java OutputStream
提问by Ciryon
I am about to write junit tests for a XML parsing Java class that outputs directly to an OutputStream. For example xmlWriter.writeString("foo");would produce something like <aTag>foo</aTag>to be written to the outputstream held inside the XmlWriter instance. The question is how to test this behaviour. One solution would of course be to let the OutputStream be a FileOutputStream and then read the results by opening the written file, but it isn't very elegant.
我即将为直接输出到 OutputStream 的 XML 解析 Java 类编写 junit 测试。例如,xmlWriter.writeString("foo");会产生类似于<aTag>foo</aTag>写入 XmlWriter 实例中保存的输出流的内容。问题是如何测试这种行为。一种解决方案当然是让 OutputStream 成为 FileOutputStream,然后通过打开写入的文件来读取结果,但这不是很优雅。
回答by Jon Skeet
Use a ByteArrayOutputStreamand then get the data out of that using toByteArray(). This won't test howit writes to the stream (one byte at a time or as a big buffer) but usually you shouldn't care about that anyway.
使用ByteArrayOutputStream,然后使用toByteArray()从中获取数据。这不会测试它如何写入流(一次一个字节或作为一个大缓冲区),但通常你不应该关心它。
回答by eljenso
If you can pass a Writer to XmlWriter, I would pass it a StringWriter. You can query the StringWriter's contents using toString()on it.
如果您可以将 Writer 传递给 XmlWriter,我会将其传递给StringWriter. 您可以StringWriter使用toString()on查询的内容。
If you have to pass an OutputStream, you can pass a ByteArrayOutputStreamand you can also call toString()on it to get its contents as a String.
如果必须传递OutputStream,则可以传递 a ByteArrayOutputStream,也可以调用toString()它以将其内容作为字符串获取。
Then you can code something like:
然后你可以编写类似的代码:
public void testSomething()
{
Writer sw = new StringWriter();
XmlWriter xw = new XmlWriter(sw);
...
xw.writeString("foo");
...
assertEquals("...<aTag>foo</aTag>...", sw.toString());
}
回答by Dherik
It's simple. As @JonSkeet said:
这很简单。正如@JonSkeet 所说:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// pass the baos to be writed with "value", for this example
byte[] byteArray = baos.toByteArray();
Assert.assertEquals("value", new String(byteArray));

