Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing what's written to a Java OutputStream

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.

like image 995
Ciryon Avatar asked Oct 22 '08 09:10

Ciryon


People also ask

How does java OutputStream work?

An output stream accepts output bytes and sends them to some sink. Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output. Methods: void close() : Closes this output stream and releases any system resources associated with this stream.

What is the OutputStream in java?

The OutputStream class of the java.io package is an abstract superclass that represents an output stream of bytes. Since OutputStream is an abstract class, it is not useful by itself. However, its subclasses can be used to write data.


2 Answers

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.

like image 142
Jon Skeet Avatar answered Oct 15 '22 19:10

Jon Skeet


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()); } 
like image 36
eljenso Avatar answered Oct 15 '22 19:10

eljenso