Mockito with functions in Dart

Issue

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?

Solution

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

Answered By – brianegan

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *