如何在 Flutter 中对依赖于 3rd-Party-Package 的代码进行单元测试?

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() 使其 return 一些满足你测试的结果

有关如何模拟检查的更多信息this and this

如何模拟的简短示例:

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
          },
        );
}