测试使用流的方法的最佳方法

时间:2017-01-01 15:24:32

标签: java junit

我有这个方法

    void sort(InputStream in, OutputStream out, Comparator<?> comparator) throws IOException;

根据提供的比较器对输出流(相同格式)中的输入流(XML数据)进行排序。

由于我是Junit的初学者,你会如何测试这种方法?如果你能提供一些代码片段会很棒。

1 个答案:

答案 0 :(得分:1)

一般测试公众可观察行为的单元测试

在你的情况下,它是与两个流的交互。

  • 为两个版本创建模拟(通常我建议使用模拟框架,但标准库中有一些非常适合此目的的简单实现......)
  • 配置inputStream以错误顺序返回数据。
  • 检查输出流是否按正确顺序获取数据。

这可能是这样的:

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"));
   }
}
相关问题