Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: testing shared preferences

I'm trying to test this function:

 void store(String x, String y) async {
    Map<String, dynamic> map = {
      'x': x,
      'y': y,
    };
    var jsonString = json.encode(map);
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('fileName', jsonString);
  }

I saw that I can populate the shared preferences with

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

But I didn't understand how to use, expecially in my case.

like image 640
Little Monkey Avatar asked Oct 13 '18 14:10

Little Monkey


People also ask

What is shared preferences in Flutter?

SharedPreferences. shared_preferences is a Flutter plugin that allows you to save data in a key-value format so you can easily retrieve it later. Behind the scenes, it uses the aptly named SharedPreferences on Android and the similar UserDefaults on iOS.


2 Answers

You can use SharedPreferences.setMockInitialValues for your test

test('Can Create Preferences', () async{

    SharedPreferences.setMockInitialValues({}); //set values here
    SharedPreferences pref = await SharedPreferences.getInstance();
    bool working = false;
    String name = 'john';
    pref.setBool('working', working);
    pref.setString('name', name);


    expect(pref.getBool('working'), false);
    expect(pref.getString('name'), 'john');
  });
like image 83
nonybrighto Avatar answered Sep 18 '22 12:09

nonybrighto


Thanks to nonybrighto for the helpful answer.

I ran into trouble trying to set initial values in shared preferences using:

SharedPreferences.setMockInitialValues({
  "key": "value"
});

It appears that the shared_preferences plugin expects keys to have the prefix flutter.. This therefore needs adding to your own keys if mocking using the above method.

See line 20 here for evidence of this: https://github.com/flutter/plugins/blob/2ea4bc8f8b5ae652f02e3db91b4b0adbdd499357/packages/shared_preferences/shared_preferences/lib/shared_preferences.dart

like image 43
Richard Thomas Avatar answered Sep 19 '22 12:09

Richard Thomas