测试写入Java OutputStream的内容 [英] Testing what's written to a Java OutputStream
问题描述
我即将为直接输出到OutputStream的XML解析Java类编写junit测试。例如 xmlWriter.writeString(foo);
会产生类似< aTag> foo< / aTag>
的内容写入XmlWriter实例中保存的输出流。问题是如何测试这种行为。一个解决方案当然是让OutputStream成为FileOutputStream然后通过打开写入的文件来读取结果,但它不是很优雅。
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.
推荐答案
使用 ByteArrayOutputStream 然后使用 toByteArray()。这不会测试如何它写入流(一次一个字节或作为一个大缓冲区),但通常你不应该关心它。
Use a ByteArrayOutputStream and then get the data out of that using toByteArray(). This won't test how it writes to the stream (one byte at a time or as a big buffer) but usually you shouldn't care about that anyway.
这篇关于测试写入Java OutputStream的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!