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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With