如果您觉得文章对您有帮助,欢迎 👍, 我的 Github.
最近在开发这个库的时候,需要使用 path_provider 这个插件库,用来获取各个平台的存储路径
在跑Unit test时,发现下面这个错误:
ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
If you're running an application and need to access the binary messenger before `runApp()` has been called (for example, during plugin initialization), then you need to explicitly call the `WidgetsFlutterBinding.ensureInitialized()` first.
...
简单分析,flutter插件是通过平台通道进行通信的,在unit test中自然没有通信条件,从而报错。
解决办法
对使用的方法简单封装下,例如
class PathProvider {
Future<String> getSavedPath() async {
return (await getApplicationSupportDirectory()).absolute.path;
}
}
static Future<bool> init(
{PathProvider provider}) async {
if (provider == null) {
provider = PathProvider();
}
final path = await provider.getSavedPath();
//...使用 path
return true;
}
正常代码中使用
void main() async {
await init();
}
unit test中使用mock替换具体实现
添加依赖
dev_dependencies:
# mock
mockito: ^4.1.1
// Mock class
class MockPathProvider extends Mock implements PathProvider {
@override
Future<String> getSavedPath() async {
return "./path_provider";
}
//...替换其他方法
}
void main() async {
await init(provider: MockPathProvider());
}
问题至此解决。