![](/img/trans.png)
[英]Flutter - Future<void> can not be assigned to the parameter type Future<void> Function()
[英]How can I unit test Future<void> function in flutter?
我有 Future function 稱為 addRating 將數據添加到 Firestore,我是在 flutter 中測試的新手,我該如何實現?
Function 我要測試:
Future<void> addRating(RatingModel rating) async {
await _firestore.collection('rating').doc(rating.ratingId).set(rating.toJson());
}
我試過的:
final firestore = FakeFirebaseFirestore();
test('can add to firestore', () async{
RatingRepository ratingRepository = RatingRepository(firestore: firestore);
RatingModel model = RatingModel(feedback: 'test', merchantId: '1', orderId: '1', rating: 1, ratingId: '1');
await expectLater(()async{await ratingRepository.addRating(model);}, isNull);
});
你快到了。 使用await
的想法是正確的。 您可以執行以下操作
final firestore = FakeFirebaseFirestore();
test('can add to firestore', () async{
RatingRepository ratingRepository = RatingRepository(firestore: firestore);
RatingModel model = RatingModel(feedback: 'test', merchantId: '1', orderId: '1', rating: 1, ratingId: '1');
await ratingRepository.addRating(model);
expect(...); // Whatever condition should be fullfilled afterwards.
});
這是有效的,因為測試 function itslef 被標記為async
,允許您在 function 主體內使用 await 。
最后一行當然取決於您的用例。 是否應該提高評級? 它應該存儲在某個地方嗎?
我想如果你什么都不期待,那么你只需要驗證 function 是否被調用:
verify(()async{await ratingRepository.addRating(model);})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.