DEV Community

loading...

Widget testing when your app needs access to directories.

Reme Le Hane
Cyclist, Runner, Developer, Amateur Photographer. #Flutter
Originally published at Medium on ・2 min read

Many times in an application you would have a need to store files, temporarily or even permanently. For this, you are probably going to be using path_provider, however, those methods are not going to simply work when running a widget test.

Thankfully it is quite simply to be able to mock that and provide your own path for use during testing.

There is quite a simple way to do this and it is done with MethodChannel

const TEST\_MOCK\_STORAGE = './test/fixtures/core';

const channel = MethodChannel(
  'plugins.flutter.io/path\_provider',
);
channel.setMockMethodCallHandler((MethodCall methodCall) async {
  return TEST\_MOCK\_STORAGE;
});
Enter fullscreen mode Exit fullscreen mode

You simply need to provide the channel you wish to mock, in this case, it is pluggins.flutter.io/path_provider and use the setMockMethodCallHandler where you can either provide specific calls and values to return or in this case provide a catch-all response, in this case, what will happen is any request to path provider will return the provided path.

So whether you are getApplicationDocumentssDirectory or getExternalStorageDirectory the result is going to be ./test/fixtures/core.

An important thing to note is that this MethodChannel call needs to be run in each test that will be accessing the path, if it’s only a single test then it is fine to provide that directly inside the main().

In our case, however, there is quite a bit of the application that relies on accessing the Documents Directory. For that reason, we have added that method into a setUpTest function that we pass into the setUp((){ }) part of the widget test.

void main() {
  setUp(() async {
    await setupTest();
  });

  testWidgets(
    'Should render [SampleWidget]',
    (WidgetTester tester) async {
      await tester.pumpWidget(SampleWidget());

      await tester.pumpAndSettle();
    },
  );
}
Enter fullscreen mode Exit fullscreen mode

If you are needing access to files, ensure they exist in the path you have provided as the mock result path, after that you should have no problems testing any Widgetsthat need access to those files.


Discussion (0)