加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在flutter上测试shared_preferences

发布时间:2020-12-14 14:49:29 所属栏目:百科 来源:网络整理
导读:我正在写一个颤动的应用程序,我在编写测试时遇到了这个问题.该方法应该将数据写入TextFields并点击一个按钮,将该数据保存在SharedPrefs中: testWidgets('Click on login saves the credentials',(WidgetTester tester) async { await tester.pumpWidget(MyA
我正在写一个颤动的应用程序,我在编写测试时遇到了这个问题.该方法应该将数据写入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');
  });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读