flutter - 如何撤消“setMockInitialValues”
问题描述
我正在使用shared_preferences来存储一些简单的数据。
当我尝试对此进行测试时,我遇到了一个问题。
测试 1适用于快乐的流程。我SharedPreferences.setMockInitialValues(data);
用来设置一些初始数据并很好地检索它。
测试 2PlatformException
测试抛出a 时会发生什么。我发现能够伪造这个我可以PlatformChannel
像这样挂钩:
sharedPreferencesMethodChannel
.setMockMethodCallHandler((MethodCall methodCall) async {
throw genericPlatformException;
});
当我只运行测试 2 时,它按预期工作,但如果我同时运行两个测试,测试 2 将失败。如果在测试 1 中我不使用SharedPreferences.setMockInitialValues(data);
和运行两者,测试 2 将通过。
所以我想我只需要重置或撤消每个测试的模拟值设置......但我该怎么做呢?似乎将它们设置一次是永久性的。
解决方案
这似乎是不可能的。
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';
}
}
推荐阅读
- python - 通过读取 csv 文件显示树
- java - 使用 Java 的 File 生成特定大小的文件
- python - 如何在 ubuntu 18.04 上安装 2 个 python 版本?(不使用虚拟环境)
- php - 奇怪的价值变化 - 通过引用调用?
- android - Android 实时数据库检查
- webpack - Webpack ts-loader 通过热模块替换忽略类型更改
- angular - 将选定的行元素从角度数据表传递到弹簧靴
- powershell - 使用 Invoke-Command 时的提升权限
- java - 使用java合并excel文件中的单元格
- ansible - 从 url 检查文件的校验和