Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock function in flutter test

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?

like image 882
Code Spirit Avatar asked Oct 15 '25 16:10

Code Spirit


1 Answers

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

like image 168
Valentin Vignal Avatar answered Oct 17 '25 06:10

Valentin Vignal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!