在flutter上测试shared_preferences

在flutter上测试shared_preferences,第1张

概述我正在写一个颤动的应用程序,我在编写测试时遇到了这个问题.该方法应该将数据写入TextFields并点击一个按钮,将该数据保存在SharedPrefs中: testWidgets('Click on login saves the credentials', (WidgetTester tester) async { await tester.pumpWidget(MyApp 我正在写一个颤动的应用程序,我在编写测试时遇到了这个问题.该方法应该将数据写入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');  });}

原始答案:

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');  });
总结

以上是内存溢出为你收集整理的在flutter上测试shared_preferences全部内容,希望文章能够帮你解决在flutter上测试shared_preferences所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1000523.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-21
下一篇2022-05-21

发表评论

登录后才能评论

评论列表(0条)

    保存