如何在颤动测试中模拟功能

How to mock function in flutter test

如何在 flutter 中模拟一个函数并验证它已被调用 n 次?

我试过从 mockito 实现 Mock 但它只会抛出错误:

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

  });

作为解决方法,我只是手动跟踪呼叫:


test("...", () {
   int calls = 0;
   bloc = EntityListBloc(onListen: () => calls++);

   // ...

   expect(calls, equals(1));
});

有没有办法为 flutter 测试创建简单的模拟函数?

你可以这样做:

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