[英]How to Unit Test code that is dependent on 3rd-Party-Package in Flutter?
如何測試 flutter 中的代碼,這取決於 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
},
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.