查找组件
要在测试环境中定位小部件,请使用 Finder
类。虽然可以编写自己的 Finder
类,但通常使用 flutter_test
包提供的工具来定位小部件会更方便。
在小部件测试的 flutter run
会话期间,您还可以交互式地点击屏幕的某些部分,让 Flutter 工具打印出建议的 Finder
。
本示例将介绍 find
常量(由 flutter_test
包提供),并演示如何使用它提供的一些 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);
});
}