felangel / mocktail

A mock library for Dart inspired by mockito
https://pub.dev/packages/mocktail
MIT License
617 stars 81 forks source link

[QUESTION] How to store more than one canned response when stubbing a method that will be inside a loop? #115

Closed igorvidottof closed 2 years ago

igorvidottof commented 2 years ago

Is there a way of stubbing a method to return a new value every time it's called? For example:

numbers.forEach((number) {
  int newNumber = getNewNumberBasedOnHeavyLogic(number);
  if(newNumber == somevalue) {
    // do something
  }
  else {
    // do something else
  }
});

As a reference, I found this similar question solved for Java: https://stackoverflow.com/questions/64021732/how-to-mock-the-function-in-a-loop-using-mockito-in-java-to-return-different-val

Thank you in advance!

felangel commented 2 years ago

Hi @igorvidottof 👋 Thanks for opening an issue!

There's an example of dynamically creating stubs in the README:

// You can calculate stubs dynamically.
final sounds = ['purrr', 'meow'];
when(() => cat.sound()).thenAnswer((_) => sounds.removeAt(0));
expect(cat.sound(), 'purrr');
expect(cat.sound(), 'meow');

Let me know if that helps 👍

igorvidottof commented 2 years ago

Hi @felangel!

Thank you so much for answering this so fast! That is just what I was looking for! I didn't quite realize it was there haha, sorry about that. Well done for the package! 🙌 🙌