首页 > 解决方案 > 如何撤消“setMockInitialValues”

问题描述

我正在使用shared_preferences来存储一些简单的数据。

当我尝试对此进行测试时,我遇到了一个问题。

测试 1适用于快乐的流程。我SharedPreferences.setMockInitialValues(data);用来设置一些初始数据并很好地检索它。

测试 2PlatformException测试抛出a 时会发生什么。我发现能够伪造这个我可以PlatformChannel像这样挂钩:

sharedPreferencesMethodChannel
        .setMockMethodCallHandler((MethodCall methodCall) async {
      throw genericPlatformException;
    });

当我只运行测试 2 时,它按预期工作,但如果我同时运行两个测试,测试 2 将失败。如果在测试 1 中我不使用SharedPreferences.setMockInitialValues(data);和运行两者,测试 2 将通过。

所以我想我只需要重置或撤消每个测试的模拟值设置......但我该怎么做呢?似乎将它们设置一次是永久性的。

标签: flutterunit-testingsharedpreferences

解决方案


这似乎是不可能的。

PlatformsExceptions可以使用模拟来完成测试行为。

我只是允许在我的包装类上设置一个模拟 SharedPreferences,所以我SharedPreferences在测试时不会与真实的交互。

class WrapperClass {
  SharedPreferences? _sharedPreferences;

  set mockSharedPreferences(SharedPreferences mock) {
    _sharedPreferences = mock;
  }

  Future<String> getData() async {
    // The real SharedPreferences only gets called if no mock was set
    _sharedPreferences ??= await SharedPreferences.getInstance();
    return _sharedPreferences!.getString('my_key') ?? 'default';
  }
}

推荐阅读