gpt4 book ai didi

在 flutter 上测试 shared_preferences

转载 作者:IT老高 更新时间:2023-10-28 12:34:36 25 4
gpt4 key购买 nike

我正在编写一个 flutter 应用程序,并且在编写测试时遇到了这个问题。此方法应该将数据写入 TextFields 并点击一个将这些数据保存在 SharedPrefs 中的按钮:

testWidgets('Click on login saves the credentials',
(WidgetTester tester) async {

await tester.pumpWidget(MyApp());

await tester.enterText(find.byKey(Key('phoneInput')), 'test');
await tester.enterText(find.byKey(Key('passwordInput')), 'test');
await tester.tap(find.byIcon(Icons.lock));

SharedPreferences prefs = await SharedPreferences.getInstance();
expect(prefs.getString('phone'), 'test');
expect(prefs.getString('password'), 'test');
});

此测试将无法获取 SharedPreferences 实例并出现此错误:

The following TimeoutException was thrown running a test:
TimeoutException after 0:00:03.500000: The test exceeded the timeout. It may have hung.
Consider using "addTime" to increase the timeout before expensive operations.

更新:似乎问题实际上不是超时,因为即使有 60 秒,测试也无法解析 SharedPreferences 实例。

最佳答案

您需要从 shared_preferences 模拟 getAll(引用:https://pub.dartlang.org/packages/shared_preferences)

示例代码如下:

import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart'; // <-- needed for `MethodChannel`

void main() {

setUpAll(() {
const MethodChannel('plugins.flutter.io/shared_preferences')
.setMockMethodCallHandler((MethodCall methodCall) async {
if (methodCall.method == 'getAll') {
return <String, dynamic>{}; // set initial values here if desired
}
return null;
});
});

testWidgets('Click on login saves the credentials',
(WidgetTester tester) async {
await tester.pumpWidget(MyApp());

await tester.enterText(find.byKey(Key('phoneInput')), 'test');
await tester.enterText(find.byKey(Key('passwordInput')), 'test');
await tester.tap(find.byIcon(Icons.lock));

SharedPreferences prefs = await SharedPreferences.getInstance();
expect(prefs.getString('phone'), 'test');
expect(prefs.getString('password'), 'test');
});
}



原答案:


testWidgets('Click on login saves the credentials',
(WidgetTester tester) async {
final AutomatedTestWidgetsFlutterBinding binding = tester.binding;
binding.addTime(const Duration(seconds: 10)); // or longer if needed
await tester.pumpWidget(MyApp());

await tester.enterText(find.byKey(Key('phoneInput')), 'test');
await tester.enterText(find.byKey(Key('passwordInput')), 'test');
await tester.tap(find.byIcon(Icons.lock));

SharedPreferences prefs = await SharedPreferences.getInstance();
expect(prefs.getString('phone'), 'test');
expect(prefs.getString('password'), 'test');
});

关于在 flutter 上测试 shared_preferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54188939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com