'Dart Mockito when first, second, ... n calls, return different value

In Java Mockito, you can Mock a different returned value for each call like this:

when(myMock.doTheCall())
   .thenReturn("You failed")
   .thenReturn("Success");

Or like this:

when(myMock.doTheCall()).thenReturn("Success", "you failed");

Source: Simulate first call fails, second call succeeds

I wonder how to achieve the same in Dart Mockito. I could not find a documentation for that



Solution 1:[1]

You can read the mockito documentation here: https://pub.dev/documentation/mockito/latest/ The solution is using an ordered array of the responses you want. For your example:

final responses = ["You failed", "Success"];
when(myMock.doTheCall()).thenAnswer((_)=>responses.removeAt(0))

This also works with async responses (adding the async word to the method thenAnswer(...)).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1