Testing in Flutter

Sep 19 2023 · Dart 2.19.3, Flutter 3.7.6, Android Studio 2021.3.1, Visual Studio Code 1.7.4

Part 3: Write Widget Tests

13. Test Quotes Page

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 12. Mock Quotes Data & Override Riverpod Dependencies Next episode: 14. Reuse Widget Test in Integration Test

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

Now let us start with testing the quotes. Head over test folder and create a new file named quotes_page_test.dart. To test the quotes page first, we will have to Mock the quotes so that we can populate the quotes list on the quotes page.

class MockQuotesService extends Mock implements QuotesService {}

Widget createWidgetUnderTest() {
  return ProviderScope(
      overrides: [
        quotesNotifierProvider
            .overrideWith((ref) => QuotesNotifier(mockQuotesService))
      ],
      child: MaterialApp(
        home: AllQuotesScreen(),
      ));
}
testWidgets('All Quotes Widget Test', (WidgetTester tester) async {
  await tester.pumpWidget(createWidgetUnderTest());
});
void getQuotesAdter2secondsDelay() {
 when(() => mockQuotesService.getQuotes()).thenAnswer((_) async {
   return await Future.delayed(
       const Duration(seconds: 2), () => mockQuotesForTesting);
 });
}
void getQuotesAdter2secondsDelay() {
  when(() => mockQuotesService.getQuotes()).thenAnswer((_) async {
    return await Future.delayed(
        const Duration(seconds: 2), () => mockQuotesForTesting);
  });
}


  // Pumping All Quotes
Widget createWidgetUnderTest() {
  return ProviderScope(
      overrides: [
        quotesNotifierProvider
            .overrideWith((ref) => QuotesNotifier(mockQuotesService))
      ],
      child: MaterialApp(
        home: AllQuotesScreen(),
      ));
}

// Mock the Quotes
getQuotesAdter2secondsDelay();

// Pump All Quotes screen
await tester.pumpWidget(createWidgetUnderTest());
 expect(find.text('All Quotes'), findsOneWidget);
await tester.pump(const Duration(seconds: 1));
expect(find.byKey(quotesCircularProgressKey), findsOneWidget);
await tester.pumpAndSettle();
expect(find.byKey(quotesCircularProgressKey), findsNothing);
expect(find.text('Test Quote 1'), findsOneWidget);
expect(find.text('Test Quote 2'), findsOneWidget);
expect(find.text('Test Quote 3'), findsOneWidget);