首页 > 解决方案 > 如何在 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>

标签: unit-testingflutterflutter-test

解决方案


您需要模拟被测试代码调用的所有方法(如果它调用它们并取决于它们的结果)

在您的情况下,您应该模拟该方法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
          },
        );
}

推荐阅读