unit-testing - 如何在 Flutter 中对依赖于 3rd-Party-Package 的代码进行单元测试?
问题描述
如何在颤振中测试代码,这取决于 path_provider 插件?
对依赖于 path_provider 插件的代码执行测试时,出现以下错误:
MissingPluginException(No implementation found for method getStorageDirectory on channel plugins.flutter.io/path_provider)
package:flutter/src/services/platform_channel.dart 319:7 MethodChannel.invokeMethod
===== asynchronous gap ===========================
dart:async _asyncErrorWrapperHelper
package: mypackage someClass.save
unit_tests/converter_test.dart 19:22
main.<fn>
解决方案
您需要模拟被测试代码调用的所有方法(如果它调用它们并取决于它们的结果)
在您的情况下,您应该模拟该方法getStorageDirectory()
以使其返回一些满足您的测试的结果
如何模拟的一个简短示例:
class MyRepo{
int myMethod(){
return 0;
}
}
class MockRepo extends Mock implements MyRepo{}
void main(){
MockRepo mockRepo = MockRepo();
test('should test some behaviour',
() async {
// arrange
when(mockRepo.myMethod()).thenAnswer(1);//in the test when myMethod is called it will return 1 and not 0
// act
//here put some method that will invoke myMethod on the MockRepo and not on the real repo
// assert
verify(mockRepo.myMethod());//verify that myMethod was called
},
);
}
推荐阅读
- visual-studio-code - 向上/向下移动打开编辑器的 VSCode 快捷方式(不是组,而是打开编辑器)
- python - Python-检查值在无限范围内
- python - 通过 for 循环后计数器变量没有改变
- javascript - 检测数组元素中的组合
- drake - Drake 中的差动驱动机器人仿真
- objective-c - 实施 FCM 时,没有为应用程序错误找到有效的“aps-environment”权利字符串
- python - 在具有多个键的字典内循环
- snowflake-cloud-data-platform - 如何找到运行最多查询的用户/角色
- powershell - 优先启动进程
- css - 带有边框图像的边框半径