Search code examples
unit-testingtestingdartflutter

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.


Solution

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