I'm in the process of writing a Flutter app with some extensive unit test coverage.
I'm using Mockito to mock my classes.
Coming from a Java (Android) world where I can use Mockito to chain calls to return different values on subsequent calls.
I would expect this to work.
import 'package:test/test.dart';
import 'package:mockito/mockito.dart';
void main() {
test("some string test", () {
StringProvider strProvider = MockStringProvider();
when(strProvider.randomStr()).thenReturn("hello");
when(strProvider.randomStr()).thenReturn("world");
expect(strProvider.randomStr(), "hello");
expect(strProvider.randomStr(), "world");
});
}
class StringProvider {
String randomStr() => "real implementation";
}
class MockStringProvider extends Mock implements StringProvider {}
However it throws:
Expected: 'hello'
Actual: 'world'
Which: is different.
The only working way I found that works is by keeping track myself.
void main() {
test("some string test", () {
StringProvider strProvider = MockStringProvider();
var invocations = 0;
when(strProvider.randomStr()).thenAnswer((_) {
var a = '';
if (invocations == 0) {
a = 'hello';
} else {
a = 'world';
}
invocations++;
return a;
});
expect(strProvider.randomStr(), "hello");
expect(strProvider.randomStr(), "world");
});
}
00:01 +1: All tests passed!
Is there a better way?