Skip to content
Advertisement

Using Mockito with multiple calls to the same method with the same arguments

Is there a way to have a stubbed method return different objects on subsequent invocations? I’d like to do this to test nondeterminate responses from an ExecutorCompletionService. i.e. to test that irrespective of the return order of the methods, the outcome remains constant.

The code I’m looking to test looks something like this.

JavaScript

Advertisement

Answer

You can do that using the thenAnswer method (when chaining with when):

JavaScript

Or using the equivalent, static doAnswer method:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement