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