Mockito - Returning a different value for the same function invocation

Mockito - Returning a different value for the same function invocation

When we are performing unit testing we generally stub or mock external classes, methods, and their return value. Sometimes one can encounter a scenario where different return values for the same method are expected. For this particular case, we can use the overloaded method thenReturn of Mockito

Mockito.when(<class_instance_name>.<method_name>(<method_args>))
       .thenReturn(T val1, T...values)

The above method ensures that you get a different value for each method invocation. If the number of method invocations exceeds the provided number of return values, then the last provided value in thenReturn is returned for each subsequent call.