查找组件
如何使用 Finder 类进行组件测试。
要在测试环境中定位组件,请使用 Finder 类。虽然可以编写自己的 Finder 类,但通常使用 flutter_test 库提供的工具来定位组件会更方便。
在组件测试的 flutter run 会话期间,你还可以交互式地点击屏幕部分,让 Flutter 工具打印出建议使用的 Finder。
本篇指南介绍了 flutter_test 库提供的 find 常量,并演示了如何使用它提供的一些 Finder。有关可用查找器的完整列表,请参阅 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);
});
}