查找组件
要在测试环境中定位小部件,请使用 Finder
类。虽然可以编写自己的 Finder
类,但通常使用 flutter_test
包提供的工具来定位小部件会更方便。
在小部件测试的 flutter run
会话期间,您还可以通过点击屏幕的各个部分来交互式地让 Flutter 工具打印建议的 Finder
。
本指南着重介绍 flutter_test
包提供的 find
常量,并演示如何使用它提供的一些 Finders
。有关可用查找器的完整列表,请参阅 CommonFinders
文档。
如果您不熟悉小部件测试以及 Finder
类在其中的作用,请回顾 小部件测试简介 指南。
本示例将采取以下步骤
- 查找
Text
小部件。 - 查找具有特定
Key
的小部件。 - 查找特定的小部件实例。
1. 查找 Text
小部件
#在测试中,您经常需要查找包含特定文本的小部件。这正是 find.text()
方法的作用。它创建一个 Finder
,用于搜索显示特定 String
文本的小部件。
testWidgets('finds a Text widget', (tester) async {
// Build an App with a Text widget that displays the letter 'H'.
await tester.pumpWidget(const MaterialApp(home: Scaffold(body: Text('H'))));
// Find a widget that displays the letter 'H'.
expect(find.text('H'), findsOneWidget);
});
2. 查找具有特定 Key
的小部件
#在某些情况下,您可能希望根据提供给小部件的 Key 来查找小部件。当显示同一小部件的多个实例时,这可能非常有用。例如,ListView
可能会显示几个包含相同文本的 Text
小部件。
在这种情况下,请为列表中的每个小部件提供一个 Key
。这允许应用程序唯一地标识一个特定的小部件,从而更易于在测试环境中查找该小部件。
testWidgets('finds a widget using a Key', (tester) async {
// Define the test key.
const testKey = Key('K');
// Build a MaterialApp with the testKey.
await tester.pumpWidget(MaterialApp(key: testKey, home: Container()));
// Find the MaterialApp widget using the testKey.
expect(find.byKey(testKey), findsOneWidget);
});
3. 查找特定的小部件实例
#最后,您可能还对定位特定小部件实例感兴趣。例如,在创建接受 child
属性的小部件时,并且您希望确保自己正确渲染了 child
小部件,这会很有用。
testWidgets('finds a specific instance', (tester) async {
const childWidget = Padding(padding: EdgeInsets.zero);
// Provide the childWidget to the Container.
await tester.pumpWidget(Container(child: childWidget));
// Search for the childWidget in the tree and verify it exists.
expect(find.byWidget(childWidget), findsOneWidget);
});
概述
#flutter_test
包提供的 find
常量提供了多种在测试环境中定位小部件的方法。本指南演示了其中三种方法,此外还有更多用于不同目的的方法。
如果上述示例不能满足您的特定用例,请参阅 CommonFinders
文档 以查看所有可用方法。
完整示例
#import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('finds a Text widget', (tester) async {
// Build an App with a Text widget that displays the letter 'H'.
await tester.pumpWidget(const MaterialApp(home: Scaffold(body: Text('H'))));
// Find a widget that displays the letter 'H'.
expect(find.text('H'), findsOneWidget);
});
testWidgets('finds a widget using a Key', (tester) async {
// Define the test key.
const testKey = Key('K');
// Build a MaterialApp with the testKey.
await tester.pumpWidget(MaterialApp(key: testKey, home: Container()));
// Find the MaterialApp widget using the testKey.
expect(find.byKey(testKey), findsOneWidget);
});
testWidgets('finds a specific instance', (tester) async {
const childWidget = Padding(padding: EdgeInsets.zero);
// Provide the childWidget to the Container.
await tester.pumpWidget(Container(child: childWidget));
// Search for the childWidget in the tree and verify it exists.
expect(find.byWidget(childWidget), findsOneWidget);
});
}