Mastering Mockito: Returning Fresh Stream For Multiple Calls To Mocked Method
When we mock a method that returns a Stream
we need to make sure we return a fresh Stream
on each invocation to support multiple calls to the mocked method. If we don’t do that, the stream will be closed after the first call and subsequent calls will throw exceptions. We can chain multiple thenReturn
calls to return a fresh Stream
each time the mocked method is invoked. Or we can use multiple arguments with the thenReturn
method, where each argument is returned based on the number of times the mocked method is invoked. So on the first invocation the first argument is returned, on second invocation the second argument and so on. This works when we know the exact number of invocations in advance. But if we want to be more flexible and want to support any number of invocations, then we can use thenAnswer
method. This method needs an Answer
implementation that returns a value on each invocation. The Answer
interface is a functional interface with only one method that needs to be implemented. We can rely on a function call to implement the Answer
interface where the function gets a InvocationOnMock
object as parameter and returns a value. As the function is called each time the mocked method is invoked, we can return a Stream
that will be new each time.