Flutter Test MissingPluginException

Loo*_*oop 8 dart flutter

运行依赖于SharedPreferences插件的测试总是会导致

MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
Run Code Online (Sandbox Code Playgroud)

我的pubspec.yaml

dev_dependencies:
  flutter_test:
     sdk: flutter

dependencies:
  flutter:
     sdk: flutter
  shared_preferences: 0.2.3
Run Code Online (Sandbox Code Playgroud)

代码在应用程序本身中工作正常.我是否缺少一些我需要做的事情才能运行使用插件的测试?

Col*_*son 27

如果您使用的是0.2.4及更高版本的shared_preferences,请使用setMockInitialValues:

SharedPreferences.setMockInitialValues({}); // set initial values here if desired
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)

  • 有人可以解释为什么这有效吗?我感觉就像旧的 CS 模因说“我的代码不起作用,我不知道为什么,现在它可以工作,我不知道为什么”。 (3认同)

小智 6

我对 flutter_secure_storage 插件遇到了完全相同的问题。我认为问题在于,使用这两个插件时,您都依赖于手机或模拟器上的存储(而不是应用程序中的存储),因此它在您的测试环境中不可用。尝试通过执行直接运行测试flutter run your_test_file.dart。根据https://flutter.io/testing/,这应该“在您首选的运行时环境(例如模拟器或设备)中”执行您的测试。它对我来说非常有效。


Jav*_*haq 6

@西曼谢谢

版本 shared_preferences: ^0.5.12

Flutter App 主函数内函数SharedPreferences.setMockInitialValues({}); 之前的广告runApp()

为我修复了这个错误

在此输入图像描述

  • 如果您保存登录用户的数据,它不会解决任何问题。每次他们打开应用程序时都会登录 (3认同)