Chain multiple calls with same arguments to return different results Chain multiple calls with same arguments to return different results flutter flutter

Chain multiple calls with same arguments to return different results


Use a list and return the answers with removeAt:

import 'package:test/test.dart';import 'package:mockito/mockito.dart';void main() {  test("some string test", () {    StringProvider strProvider = MockStringProvider();    var answers = ["hello", "world"];    when(strProvider.randomStr()).thenAnswer((_) => answers.removeAt(0));    expect(strProvider.randomStr(), "hello");    expect(strProvider.randomStr(), "world");  });}class StringProvider {  String randomStr() => "real implementation";}class MockStringProvider extends Mock implements StringProvider {}


You're not forced to call when in the start of the test:

StringProvider strProvider = MockStringProvider();when(strProvider.randomStr()).thenReturn("hello");expect(strProvider.randomStr(), "hello");when(strProvider.randomStr()).thenReturn("world");expect(strProvider.randomStr(), "world");

Mockito is dart has a different behavior. Subsequent calls override the value.