In this article, we will present a way to stub a method using Mockito to return different values on subsequent calls. This configuration is useful for testing various scenarios with nondeterminate method responses.
2. Using when(...).thenReturn(...) method
The thenReturn(...) method could take more than one argument. The first value will be returned on the first method call, then on the next call the second value will be returned, and so on. The last value will be returned repeatedly once all the other values are used up.
Let's check the example test:
3. Using doReturn method
In case we want to stub a void method or use spy instead of mock we should use doReturn(...).when(...) syntax.
The following example presents how to use different return values on spied object:
In this article, we presented how to mock a method that will return different values according to invocation count. This could be useful to test different behavior of the tested object and check how it will react to non-deterministic input values.