Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito with functions in Dart

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?

like image 705
Marcin Szałek Avatar asked Dec 08 '17 12:12

Marcin Szałek


2 Answers

I think you have three problems here:

  1. 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 the ReducerClass (which acts as a Reducer function by implementing call).
  2. You need to verify methods being called, not the whole Mock class.
  3. You must use verifyNever instead of verify(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));
  });
}
like image 86
brianegan Avatar answered Nov 04 '22 11:11

brianegan


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);

}
like image 20
manoellribeiro Avatar answered Nov 04 '22 12:11

manoellribeiro