【问题标题】:Stream has already been operated upon or closed in Mockito?Stream 是否已经在 Mockito 中运行或关闭?
【发布时间】:2019-06-20 22:30:40
【问题描述】:

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

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: 流已经被操作或关闭。

我该如何绕过它??

【问题讨论】:

  • 这个名为s 的流是从哪里来的?
  • 这个getClicks 方法永远无法编译。除此之外,问题也很明显。当您使用 Mockito 强制方法在每次调用时返回相同的流时,它会破坏任何期望它在每次调用时返回新流的方法。

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


【解决方案1】:

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

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

【讨论】:

  • 这是一个很好的解决方案。为什么它不被接受?
猜你喜欢
  • 1970-01-01
  • 2021-08-06
  • 1970-01-01
  • 2011-09-24
  • 1970-01-01
  • 2014-12-04
  • 1970-01-01
相关资源
最近更新 更多