流已在Mockito中操作或关闭?

时间:2019-01-27 21:52:10

标签: unit-testing exception java-8 mockito java-stream

我想测试一种返回流的方法。

class Foo {
    public void getClicks(boolean somecondition) {
        Stream s1 = computeAndGetAllClicks(new Date());
        if (somecondition) {
            Stream s2 = computeAndGetAllClicks(new Date());
        }
        return Stream.concat(s1, s2);
    }

    Stream computeAndGetAllClicks(Date d) {
        // return stream
    }
}

现在我为somecondition = true的情况编写了以下测试

    final ArgumentCaptor<Date> argumentCaptorTodayDate = ArgumentCaptor.forClass(Date.class);

    doReturn(Arrays.asList(new Click.Builder().build()).stream())
    .when(fooInstance)
    .addAtlasLineItem(computeAndGetAllClicks(argumentCaptorTodayDate.capture))

   final ArgumentCaptor<Date> argumentCaptorEndDate = ArgumentCaptor.forClass(Date.class);


    doReturn(Arrays.asList(new Click.Builder().build()).stream())
    .when(fooInstance)
    .addAtlasLineItem(computeAndGetAllClicks(argumentCaptorEndDate.capture))

    fooInstance.getClicks(true);

但是我得到异常:java.lang.IllegalStateException:流已被操作或关闭。

我如何解决它?

1 个答案:

答案 0 :(得分:0)

您可以使用thenAnswer并在每次调用时创建新流:

doAnswer(invocationOnMock->Arrays.asList(new Click.Builder().build()).stream())