felangel / mocktail

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

How to Mock multiple calls? #221

Closed WillACosta closed 9 months ago

WillACosta commented 9 months ago

I'm working on defining my test case in a scenario where I need to mock two calls for the same stub function. How can I achieve this? I'm thinking of something like the following code:

when(() => myFunction())
   .thenReturn("success")
   .thenReturn("failure");

I wondered how to achieve this behavior, but I couldn't find any references to it. Can anyone provide assistance or guidance on this?

felangel commented 9 months ago

Hi @WillACosta 👋 You can do something like:

import 'package:mocktail/mocktail.dart';

class MyClass {
  String foo() => 'foo';
}

class MockMyClass extends Mock implements MyClass {}

void main() {
  final MyClass myClass = MockMyClass();
  final responses = ['success', 'failure'];
  when(myClass.foo).thenAnswer((_) => responses.removeAt(0));

  print(myClass.foo()); // success
  print(myClass.foo()); // failure
}

Hope that helps 👍