[英]How to test a void function in Dart?
我是 Dart/Flutter 單元測試的新手,我想為 void function 編寫一個測試。 當函數返回一些東西時,我正在編寫這樣的測試:
test('Gets user save', () async {
final userSave = await mockSource!.getUserSave();
expect(userSave!.age, equals(20));
});
在這種情況下,可以使用上述expect
,因為getUserSave
function 返回用戶 model。
像下面這樣檢查 void/Future function 的測試是否通過失敗怎么樣? 我不能使用expect
,因為它不返回值。
Future<void> clearUserSave() async {
DatabaseClient mockDBClient = MockDatabaseClientImpl();
mockDBClient.clear();
}
我使用flutter_test
和mockito
進行測試。
通常一個void
function 會產生某種副作用。 When writing a test for a void
function, I would check whatever state is effected by the void
function before and after calling the function to be sure that the desired side effect has occurred.
在這種特定情況下,您在DatabaseClient
上調用clear
。 我不知道DatabaseClient
api 的細節,但我會在調用clear
之前構建一個測試,其中客戶端包含一些數據,然后在調用clear
之后檢查數據是否不再存在。
類似這樣的東西:
Future<void> clearUserSave() async {
DatabaseClient mockDBClient = MockDatabaseClientImpl();
mockDBClient.add(SOMEDATA);
expect(mockDBClient.hasData, true);
mockDBClient.clear();
expect(mockDBClient.hasData, false);
}
您可以在方法中添加可空變量並分配變量值,在調用方法后檢查此變量 isNotNull 是否像這樣:
test('Gets user save', () async {
await mockSource?.getUserSave();
final userSave=mockSource.user;
expect(userSave,isNotNull );
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.