我正在为一个使用 Flutter
编写的移动应用编写测试。我遵循了这个 Flutter Cookbook 上有关测试 Flutter 应用程序的指南,学习如何编写小部件和集成测试。
这个教程运行得非常完美,但我仍然卡在自己的集成测试上。
为了简化,假设我有一个只包含TextField
的应用程序:
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MyAppp',
home: Scaffold(
body: Center(child: TextField()),
),
);
}
}
我想要为这个应用程序编写一个测试。例如,我想测试以下场景:
- 打开该应用
- 检查
TextField
是否为空 - 选择
TextField
- 输入“hello, world!”
- 检查
TextField
是否包含“hello, world!”
Widget
测试,它可以正常工作:void main() {
testWidgets('TextField behavior', (WidgetTester tester) async {
// Create app
await tester.pumpWidget(MyApp());
// Find TextField, check there is 1
final textFieldFinder = find.byType(TextField);
expect(textFieldFinder, findsOneWidget);
// Retrieve TextField Widget from Finder
TextField textField = tester.widget(textFieldFinder);
// Check TextField is empty
expect(textField.controller.text, equals(""));
// Enter text
await tester.enterText(textFieldFinder, "hello, world!");
// Check TextField contains text
expect(textField.controller.text, equals("hello, world!"));
});
}
这个测试通过了,但我想写一个集成测试,做更多或更少相同的事情,以便能够在真实设备上测试它。 确实,如果这个小部件测试通过了,它很可能会在所有设备上都通过。 但是在我的应用程序中,我有更复杂的小部件和它们之间的交互,我希望能够在Android和iOS上启动测试。
我尝试使用Flutter Driver编写集成测试,但我在文档和示例中没有找到我想要的内容。
我该如何检查Widget属性,以验证我的应用程序表现符合预期?
我编写了以下示例:
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';
void main() {
group('TextField', () {
final textFieldFinder = find.byType('TextField');
FlutterDriver driver;
setUpAll(() async {
driver = await FlutterDriver.connect();
});
tearDownAll(() async {
if (driver != null) {
driver.close();
}
});
test('TextField behavior', () async {
// ??? how to check that the TextField is empty
await driver.tap(textFieldFinder);
await driver.enterText("hello, world!");
// ??? how to check that the TextField contains hello, world!
});
});
}
Flutter Cookbook教程解释了如何通过其文本检索对象,这有助于检查文本是否存在,但例如,是否可以检查Container的颜色是否为红色?Widget和集成测试之间的界限在哪里?
编写Widget测试非常直接,但我没有找到许多关于如何使用Flutter driver编写更复杂的集成测试的示例或文档。