【问题标题】:How to Unit Test code that is dependent on 3rd-Party-Package in Flutter?如何在 Flutter 中对依赖于 3rd-Party-Package 的代码进行单元测试?
【发布时间】:2020-08-02 15:47:30
【问题描述】:

如何在 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>

【问题讨论】:

标签: unit-testing flutter flutter-test


【解决方案1】:

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

在您的情况下,您应该模拟方法 getStorageDirectory() 以使其返回一些满足您的测试的结果

有关如何模拟检查 this 和 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
          },
        );
}

【讨论】:

  • 感谢您的回答 :) 我用 Mockito 创建了一个 Mock。那么如何确保在应该测试的方法中使用了 mock impl?我正在对一种名为 convert 的方法进行单元测试。此方法使用存储库类。我嘲笑了存储库类。但是如何让 convert 方法使用 mock impl?
  • 如果回答您的问题,请将答案标记为正确,我将编辑答案以显示模拟示例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-29
  • 2014-01-27
相关资源
最近更新 更多