Sub topic 1
What a widget test is and how testWidgets works
Prerequisites
This chapter assumes you know basic Dart syntax, including async and await. You should understand StatelessWidget and StatefulWidget, know how to run flutter test, and have flutter_test listed under dev_dependencies in your project.
What a widget test is
A widget test builds one widget, or a small group of widgets, in a test environment and checks what it displays and how it responds to input. Flutter builds the widget tree in memory, so the test needs no emulator or device and usually runs in well under a second.
The testWidgets function is the entry point. It works like test, but its callback receives a WidgetTester. You use that object to build widgets, find them, interact with them, and advance frames.
Building the widget under test with pumpWidget
Call tester.pumpWidget to place a widget into the test environment. Wrap the widget in MaterialApp so that Material widgets such as Scaffold and Text get the theme they need.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Text('$_count')),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _count++),
child: const Icon(Icons.add),
),
);
}
}
void main() {
testWidgets('counter starts at zero', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: Counter()));
expect(find.text('0'), findsOneWidget);
});
}Finding widgets with finders
A finder is a description of the widgets you want. Common finders include:
find.text('0')matches widgets that display that text.find.byType(FloatingActionButton)matches widgets of a class.find.byIcon(Icons.add)matches icons.find.byKey(const Key('name'))matches a widget with a specificKey.find.widgetWithText(ElevatedButton, 'Save')matches a button type that contains the given text.
Asserting with findsOneWidget, findsNothing and friends
Pass a finder to expect with a matcher:
findsOneWidgetrequires exactly one match.findsNothingrequires zero matches.findsNWidgets(3)requires exactly three matches.findsWidgetsrequires one or more matches.
Exercise
Exercise
Which finder locates a widget that displays the icon Icons.delete?
Show answer
find.byIcon(Icons.delete)