1

I have a method that produces an InputStream, after processing some bytes. This is correct from the design point of view. However, how can I unit test a method that returns an InputStream - what valid assertions can be made? (check the size, transform it into a file/bytes and check if the file is valid? what else?)

Roxana
  • 1,569
  • 3
  • 24
  • 41
  • Why would you transform it into a file? I'd try to avoid that... you can just read it into memory, surely. – Jon Skeet Jun 27 '14 at 15:05
  • 2
    The best approach depends on a lot of things.. here's a few: What's the method signature look like? Is the method mutating an existing stream, generating a stream algorithmically, or streaming a file-like resource? – Gus Jun 27 '14 at 15:08

2 Answers2

1

If the method under test is producing an InputStream the easiest way to test the returned result is to read the stream and check that the returned bytes are correct.

byte[] expectedAnswer = ...

InputStream actual = myMethodThatMakesInputStream();

ByteArrayOutputStream os = new ByteArrayOutputStream();
//Apache commons IO
IOUtils.copy(actual, os);

assertArrayEquals(expectedAnswer, os.toByteArray());

EDIT as other poster Duncan's answer uses IOUtil.toByteArray( inputstream) which internally uses the ByteArrayOutputStream route I give in my answer

dkatzel
  • 31,188
  • 3
  • 63
  • 67
1

In similar situations, I've simply read the input stream into a byte array and tested the results match what I expected.

InputStream inputStream = methodUnderTest(knownValue1, knownValue2, ...);

byte[] data = IOUtils.toByteArray(inputStream); // Apache Commons IO
assertArrayEquals(expectedData, data);

If the method under test requires input data as an input stream, I give it a ByteArrayInputStream, reading from a byte array of known value.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254