mardi 27 octobre 2020

Mock Class without instancing it Flutter Test

I'm trying to write unit tests for a Flutter application. I want to mock a class without instantiating it. Let's say I have this code:

class MyWidget extends StatelessWidget {
   @override
   build(BuildContext context) {
      final MyClass myClass = MyClass();
      final MyResult myResult = myClass.doStuff();
      return AnotherWidget(myResult);
   } 
}

class MyClass {
   MyResult doStuff() {
      // Something that returns a result
   }
}

I would like to verify that MyWidget is calling AnotherWidget with a widget test. But I also would like to mock MyClass and/or myClass.doStuff() for multiple reasons (ex: need a complex setup like API keys, Provider values, makes HTTP calls ...).

void main() {
   testWidgets('It should contain AnotherWidget', (WidgetTester tester) async {
      // I want to moke MyClass here to create a dummy one that doesn't do anything
      // and returns a dummy result when `myClass.doStuff()` is called
      await tester.pumpWidget(MyWidget());
      expect(find.byType(AnotherWidget), findsOneWidget);
   }
}

How can I achieve this ?

Aucun commentaire:

Enregistrer un commentaire