void main() { // Define a test. The TestWidgets function also provides a WidgetTester // to work with. The WidgetTester allows you to build and interact // with widgets in the test environment. testWidgets('MyWidget has a title and message', (tester) async { //建立Widget await tester.pumpWidget(const MyWidget(title: 'T', message: 'M')); }); }
3. 使用Finder查找widget
1 2 3 4 5 6 7 8 9
void main() { testWidgets('MyWidget has a title and message', (tester) async { await tester.pumpWidget(const MyWidget(title: 'T', message: 'M'));
// Create the Finders. final titleFinder = find.text('T'); final messageFinder = find.text('M'); }); }
4. 使用Matcher验证widget是否正常工作
1 2 3 4 5 6 7 8 9 10 11 12
void main() { testWidgets('MyWidget has a title and message', (tester) async { await tester.pumpWidget(const MyWidget(title: 'T', message: 'M')); final titleFinder = find.text('T'); final messageFinder = find.text('M');
// Use the `findsOneWidget` matcher provided by flutter_test to verify // that the Text widgets appear exactly once in the widget tree. expect(titleFinder, findsOneWidget); expect(messageFinder, findsOneWidget); }); }