模拟一种返回Stream的方法,并且该方法被多次调用 [英] Mock a method that returns a Stream and is called more than one time

查看:322
本文介绍了模拟一种返回Stream的方法,并且该方法被多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MyStreamClass mock = mock(MyStreamClass.class);

when(mock.streamMethod()).thenReturn(Stream.of("A", "B"));

System.out.println(""+mock.streamMethod().findFirst());
System.out.println(""+mock.streamMethod().findFirst());

findFirst的第二次调用将引发java.lang.IllegalStateException:流已被操作或关闭

the second call of findFirst will throw java.lang.IllegalStateException: stream has already been operated upon or closed

推荐答案

尝试使用thenAnswer而不是thenReturn:

Answer<Stream> answer = new Answer<Stream>() {
    public Stream answer(InvocationOnMock invocation) throws Throwable {
        return Stream.of("A", "B");
    }
};


when(mock.streamMethod()).thenAnswer(answer);

现在,将为每个对streamMethod的调用创建一个新的流.

Now a new Stream will be created for each call to streamMethod.

进一步阅读:

这是我在在Mockito中进行动态回答的文章可能是互补的.

Here is an article I wrote on Dynamic Answering in Mockito that might be complementary.

这篇关于模拟一种返回Stream的方法,并且该方法被多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆