模擬捲動操作
許多應用程式(電子郵件用戶端、音樂應用程式等)都具有內容清單功能。要使用 widget 測試來驗證清單是否包含預期內容,你需要一種方法來捲動清單以檢索指定的專案。
請在整合測試中使用 WidgetTester
類提供的方法測試捲動清單,該類別包含在 flutter_test
package 中:
在本指南中,你將學習如何捲動清單來驗證指定的 widget 是否正在顯示,還會瞭解到不同做法的利弊。
本指南會採用以下步驟:
-
建立帶有清單的應用程式。
-
編寫捲動清單的測試。
-
執行測試。
1、建立帶有清單的應用程式
本章節建立了一個顯示長清單的應用程式。為了專注於測試的編寫,這裡使用 長清單的處理 指南中建立的應用程式。如果你不確定如何使用長清單,請查閱該指南。
請在需要互動的 widget 上新增 key 以便進行整合測試。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp(
items: List<String>.generate(10000, (i) => 'Item $i'),
));
}
class MyApp extends StatelessWidget {
final List<String> items;
const MyApp({super.key, required this.items});
@override
Widget build(BuildContext context) {
const title = 'Long List';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: const Text(title),
),
body: ListView.builder(
// Add a key to the ListView. This makes it possible to
// find the list and scroll through it in the tests.
key: const Key('long_list'),
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
items[index],
// Add a key to the Text widget for each item. This makes
// it possible to look for a particular item in the list
// and verify that the text is correct
key: Key('item_${index}_text'),
),
);
},
),
),
);
}
}
2、編寫捲動清單的測試
現在,你可以編寫一個測試:捲動清單並驗證清單中是否存在指定的專案。使用 WidgetTester
類提供的 scrollUntilVisible()
方法,它可以捲動清單,直到某個指定的 widget 可見為止。這個方法非常有用,因為清單中專案的高度會根據裝置的不同而變化。
scrollUntilVisible()
方法只會緩慢地捲動清單,直至找到指定的內容。它不會假定你知道清單中所有專案的高度,也不會假定指定的 widget 會在所有裝置上渲染。
以下程式碼展示了如何使用 scrollUntilVisible()
方法在清單中查詢到指定的專案。這段程式碼位於 test/widget_test.dart
檔案中。
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:scrolling/main.dart';
void main() {
testWidgets('finds a deep item in a long list', (tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp(
items: List<String>.generate(10000, (i) => 'Item $i'),
));
final listFinder = find.byType(Scrollable);
final itemFinder = find.byKey(const ValueKey('item_50_text'));
// Scroll until the item to be found appears.
await tester.scrollUntilVisible(
itemFinder,
500.0,
scrollable: listFinder,
);
// Verify that the item contains the correct text.
expect(itemFinder, findsOneWidget);
});
}
3、執行測試
在專案根目錄下使用以下指令執行測試:
flutter test test/widget_test.dart