查詢元件
要在測試環境中定位小部件,請使用 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);
});
}