Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 颤振:测试共享偏好_Unit Testing_Testing_Dart_Flutter - Fatal编程技术网

Unit testing 颤振:测试共享偏好

Unit testing 颤振:测试共享偏好,unit-testing,testing,dart,flutter,Unit Testing,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.setStr

我正在尝试测试此函数:

 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);
  }
void存储(字符串x,字符串y)异步{
地图={
“x”:x,
y:y,
};
var jsonString=json.encode(map);
SharedReferences prefs=等待SharedReferences.getInstance();
prefs.setString('fileName',jsonString);
}
我看到我可以用

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;
  });
constmethodchannel('plugins.flatter.io/shared_preferences'))
.setMockMethodCallHandler((MethodCall MethodCall)异步{
if(methodCall.method=='getAll'){
返回{};//如果需要,在此处设置初始值
}
返回null;
});

但我不知道如何使用,特别是在我的情况下

您可以在测试中使用
SharedReferences.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');
  });

感谢nonybrighto提供了有用的答案

我在尝试使用以下工具在共享首选项中设置初始值时遇到问题:

SharedPreferences.setMockInitialValues({
  "key": "value"
});
似乎shared_preferences插件希望键具有前缀
flatter.
。因此,如果使用上述方法进行模拟,则需要将其添加到您自己的密钥中

有关这方面的证据,请参见第20行:

我在尝试测试
共享\u首选项时不断出错。是因为我正在运行
颤振测试
而没有使用设备进行测试吗?不是。您应该能够在颤振测试中使用它。你犯了什么样的错误?我已经处理好了,但我不记得是什么问题。非常感谢。如果我使用
verify(pref.setString(any,any)).called()
yes,我会出现一个错误:“用于非mockito对象”。这对莫基托不起作用。mockito需要一个扩展Mock的对象,比如
类MockSharedReference扩展Mock实现SharedReferences{}
。我真的不知道该怎么做。上面的链接是brokenThanks@SimonH-更新为指向新文件位置的链接。这不是必需的。它会自动为键添加前缀:@HashemAboonajmi是正确的,您的答案不适用于您链接的修订版(也不适用于最近的修订版)