Lit*_*key 5 testing unit-testing dart flutter
我正在尝试测试此功能:
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);
}
Run Code Online (Sandbox Code Playgroud)
我看到我可以用
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;
});
Run Code Online (Sandbox Code Playgroud)
但是我不知道如何使用,特别是在我的情况下。
你可以SharedPreferences.setMockInitialValues用来测试
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');
});
Run Code Online (Sandbox Code Playgroud)
小智 5
Thanks to nonybrighto for the helpful answer.
I ran into trouble trying to set initial values in shared preferences using:
SharedPreferences.setMockInitialValues({
"key": "value"
});
Run Code Online (Sandbox Code Playgroud)
似乎shared_preferences插件期望键具有前缀flutter.。因此,如果使用上述方法进行模拟,则需要将其添加到您自己的密钥中。
请参阅此处的第20行和第33行以获取以下证据:https : //github.com/flutter/plugins/blob/master/packages/shared_preferences/lib/shared_preferences.dart
| 归档时间: |
|
| 查看次数: |
863 次 |
| 最近记录: |