如何在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测试创建简单的模拟函数呢?
2条答案
按热度按时间8qgya5xd1#
你可以这样做:
bvjveswy2#
公认的答案是正确的,但它并不代表您可能希望用mock或fake替换顶级函数的真实场景。This article解释了如何在依赖注入组合中包含顶级函数,以便可以用mock替换这些函数。
您可以像这样编写依赖注入,并指向顶级函数,例如
launchUrl
和ioc_container。然后,你可以使用这里的答案中提到的技巧来用Mocktail进行模拟。