如何在Flutter中对依赖于第三方包装的代码进行单元测试? [英] How to Unit Test code that is dependent on 3rd-Party-Package in Flutter?

查看:175
本文介绍了如何在Flutter中对依赖于第三方包装的代码进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在flutter中测试代码,该代码取决于path_provider插件?

How can I test code in flutter, that is dependent on the path_provider plugin?

对依赖于path_provider插件的代码执行测试时,出现以下错误:

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>

推荐答案

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

You need to mock all the methods called by your code being tested if it calls them and depend on their results

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

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

有关模拟的简短示例:

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

这篇关于如何在Flutter中对依赖于第三方包装的代码进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆