简体   繁体   中英

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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