Testing what's written to a Java OutputStream

后端 未结 3 1862
既然无缘
既然无缘 2021-01-07 17:45

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

相关标签:
3条回答
  • 2021-01-07 17:51

    It's simple. As @JonSkeet said:

    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));
    
    0 讨论(0)
  • 2021-01-07 17:52

    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.

    0 讨论(0)
  • 2021-01-07 18:14

    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());
    }
    
    0 讨论(0)
提交回复
热议问题