在Flutter上测试shared_preferences

Jor*_*zco 7 testing sharedpreferences 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');
  });
Run Code Online (Sandbox Code Playgroud)

此测试将无法获得具有以下错误的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.
Run Code Online (Sandbox Code Playgroud)

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

Tru*_*inh 4

您需要模拟getAllshared_preferences参考: 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');
  });
}


Run Code Online (Sandbox Code Playgroud)

原答案:


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');
  });
Run Code Online (Sandbox Code Playgroud)