简体   繁体   中英

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?

Function I want to test:

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. 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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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