查找组件
如何使用 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);
});
}