简体   繁体   English

我如何对未来进行单元测试<void> flutter 中的 function?</void>

[英]How can I unit test Future<void> function in flutter?

I have Future function called addRating that add data to Firestore, I am new to testing in flutter, how do I achieve it?我有 Future function 称为 addRating 将数据添加到 Firestore,我是在 flutter 中测试的新手,我该如何实现?

Function I want to test: Function 我要测试:

Future<void> addRating(RatingModel rating) async {
  await _firestore.collection('rating').doc(rating.ratingId).set(rating.toJson());
}

What I have tried:我试过的:

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

You are almost there.你快到了。 The idea of using await is correct.使用await的想法是正确的。 You could do the following您可以执行以下操作

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

This works because the test function itslef is marked as async , allowing you to use await like that inside the function body.这是有效的,因为测试 function itslef 被标记为async ,允许您在 function 主体内使用 await 。

The last line of course depends on your use case.最后一行当然取决于您的用例。 Should a rating be increased?是否应该提高评级? Should it be stored somewhere?它应该存储在某个地方吗?

I think If you are expecting nothing then you just need to verify that the function is called:我想如果你什么都不期待,那么你只需要验证 function 是否被调用:

verify(()async{await ratingRepository.addRating(model);})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM