繁体   English   中英

如何对 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()以使其返回一些满足您的测试的结果

有关如何模拟检查这个这个的更多信息

如何模拟的一个简短示例:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM