Flutter: testing shared preferences Flutter: testing shared preferences flutter flutter

Flutter: testing shared preferences


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


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


I don't know if that helps you but I also lost a lot of time before finding this solution

LocalDataSourceImp.test.dart

void main(){  SharedPreferences? preference;  LocalDataSourceImp? localStorage ;setUp(() async{  preference =  await SharedPreferences.getInstance();  localStorage = LocalDataSourceImp(preference!);  SharedPreferences.setMockInitialValues({});});final token = TokenModel(data: "babakoto");test("cache Token ", ()async{  localStorage!.cacheToken(token);  final result = preference!.getString(TOKEN);  expect(result, json.encode(token.toJson()));});}

LocalDataSourceImp.dart

class LocalDataSourceImp implements LocalDataSource{  SharedPreferences pref ;  LocalDataSourceImp(this.pref);  @override  Future<void> cacheToken(TokenModel token)async {    await pref.setString(TOKEN,json.encode(token));  }}