如何在顫振中模擬一個函式并驗證它已被呼叫 n 次?
我試過Mock從 mockito 實作,但它只會拋出錯誤:
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));
});
那么有沒有一種方法可以為顫振測驗創建簡單的模擬函式?
uj5u.com熱心網友回復:
你可以做的是:
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);
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/445214.html
上一篇:如何在類init上呼叫函式
