问题
How can I test code in flutter, that is dependent on the path_provider plugin?
When executing tests for code that is dependent on the path_provider plugin, I get the following error:
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>
回答1:
You need to mock all the methods called by your code being tested if it calls them and depend on their results
in your case you should mock the method getStorageDirectory()
to make it return some result that satisfy your test
for more info on how to mock check this and this
A short example of how to mock:
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
},
);
}
来源:https://stackoverflow.com/questions/61317420/how-to-unit-test-code-that-is-dependent-on-3rd-party-package-in-flutter