Mockito with functions in Dart
4,640
Solution 1
I think you have three problems here:
- Mockito only works with Classes, not functions (see https://github.com/dart-lang/mockito/issues/62). You have some options: create a test implementation of the function, or for
redux.dart
, you can implement theReducerClass
(which acts as aReducer
function by implementingcall
). - You need to verify methods being called, not the whole Mock class.
- You must use
verifyNever
instead ofverify(X).called(0)
.
Working example:
class MockReducer extends Mock implements ReducerClass {}
main() {
test('should be able to mock a reducer', () {
final reducer = new MockReducer();
verifyNever(reducer.call(any, any));
});
}
Solution 2
If you want to just create a mocked function to use as onTap on widget test environment, with mockito you can do something like that:
abstract class MyFunction {
void call();
}
class MyFunctionMock extends Mock implements MyFunction {}
Test:
void main() {
final mock = MyFunctionMock();
...
// This is inside the the testWidgets callback
await tester.pumpWidget(
widgetToBeTested(
item: registeredListItem,
onTap: mock,
),
);
//Logic to tap the widgetToBeTested
verify(mock()).called(1);
}
Author by
Marcin Szałek
Well, I write a bit of code from time to time. On occasion, it happens to compile.
Updated on December 03, 2022Comments
-
Marcin Szałek over 1 year
I have a method that I would like to mock, however when I am trying to verify calls of this method. I get an error that says:
Used on a non-mockito object
Here is the simplified code:
test('test',() { MockReducer reducer = new MockReducer(); verify(reducer).called(0); }); class MockReducer extends Mock { call(state, action) => state; }
Why can't I do something like this?