[Solved] Best way to test a method that works with streams [closed]


Unittests in general test public observable behavior

in your case it is the interaction with the two streams.

  • create mocks for the two steams (usually I’d suggest to use a mocking framework but there are some simple implementations in the standard lib quite suitable for this purpose…)
  • Configure the inputStream to return data in false order.
  • check that the output stream got data in correct order.

This could look like this:

public class StreamsTest {

    InputStream inputStream;

    OutputStream outputStream;

    @Test
    public void sort_givenShuffledXml_returnsSortedXml() {
        // arrange
        YourClassUnderTest cut = new YourClassUnderTest();
        Comparator<?> comparator = new YourRealComparatorImpl();
        inputStream = new ByteArrayInputStream("unsortedXML".getBytes());
        outputStream = new ByteArrayOutputStream();

        // act
        cut.sort(inputStream, outputStream, comparator);

        //assert
        Assert.assertThat(outputStream.toString(),CoreMatchers.equalTo("sortedXml"));
   }
}

2

solved Best way to test a method that works with streams [closed]