在Flutter上测试shared_preferences

时间:2019-01-14 20:47:45

标签: testing flutter sharedpreferences

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

substring-before(../UserEmailAddress, '@')

此测试将无法获取具有以下错误的SharedPreferences实例:

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

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

4 个答案:

答案 0 :(得分:2)

您需要从getAll中模拟shared_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');
  });
}



原始答案:


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

答案 1 :(得分:0)

如github所述,您可以在测试开始时做类似的事情:

tester.addTime(const Duration(seconds: 10));

以下是链接和完整示例: https://github.com/flutter/flutter/issues/19175

testWidgets('MyWidget', (WidgetTester tester) async {
  final AutomatedTestWidgetsFlutterBinding binding = tester.binding;
  binding.addTime(const Duration(seconds: 10)); // or longer if needed
  await tester.pumpWidget(new MyWidget());
  await tester.tap(find.text('Save'));
  expect(find.text('Success'), findsOneWidget);
});

答案 2 :(得分:0)

您可以使用提供的模拟setMockInitialValues

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

    await tester.pumpWidget(MyApp());

    SharedPreferences.setMockInitialValues(<String, dynamic>{
      'flutter.phone': '',
      'flutter.password': '',
    });

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

答案 3 :(得分:0)

TruongSinh 提供的解决方案对我不起作用。当我尝试通过代码而非测试将值设置为 SharedPreferences 时,我遇到了错误。

所以这是对该答案的补充。您需要自己重新实现 setter:

import 'package:flutter/services.dart';

void main() {

  setUpAll(() {
    final values = <String, dynamic>{};  // set initial values here if desired
    const MethodChannel('plugins.flutter.io/shared_preferences')
        .setMockMethodCallHandler((MethodCall methodCall) async {
      if (methodCall.method == 'getAll') {
        return values;
      } else if (methodCall.method.startsWith("set")) {
        values[methodCall.arguments["key"]] = methodCall.arguments["value"];
        return true;
      }
      return null;
    });
  });

  testWidgets('Test if your code works as designed', (WidgetTester tester) async {
    ...
  });

}