How to Unit Test code that is dependent on 3rd-Party-Package in Flutter?

不羁的心 提交于 2020-05-16 01:57:31

问题


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

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>

回答1:


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

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

A short example of how to mock:

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


来源:https://stackoverflow.com/questions/61317420/how-to-unit-test-code-that-is-dependent-on-3rd-party-package-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!