views:

989

answers:

2

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.

+5  A: 

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.

Jon Skeet
+1  A: 

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.

If you have to pass an OutputStream, you can pass a ByteArrayOutputStream and you can also call toString() on it to get its contents as a String.

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());
}
eljenso