How can I mock a function in flutter and verify it has been called n times?
Ive tried implementing Mock
from mockito but it only throws errors:
class MockFunction extends Mock {
call() {}
}
test("onListen is called once when first listener is registered", () {
final onListen = MockFunction();
// Throws: Bad state: No method stub was called from within `when()`. Was a real method called, or perhaps an extension method?
when(onListen()).thenReturn(null);
bloc = EntityListBloc(onListen: onListen);
// If line with when call is removed this throws:
// Used on a non-mockito object
verify(onListen()).called(1);
});
});
As a workaround I am just manually tracking the calls:
test("...", () {
int calls = 0;
bloc = EntityListBloc(onListen: () => calls );
// ...
expect(calls, equals(1));
});
So is there a way I can create simple mock functions for flutter tests?
CodePudding user response:
What you could do is this:
class Functions {
void onListen() {}
}
class MockFunctions extends Mock implements Functions {}
void main() {
test("onListen is called once when first listener is registered", () {
final functions = MockFunctions();
when(functions.onListen()).thenReturn(null);
final bloc = EntityListBloc(onListen: functions.onListen);
verify(functions.onListen()).called(1);
});
}