Reading a resource from a file in a Flutter test

1,338

Solution 1

In the end I used the following trick (alas I can't remember where I saw it suggested to properly attribute it) to scan up the file system tree to find the project root. This way, the tests can find the data regardless of which directory the test are executed from (else I had tests that passed on the command line, but failed in Android Studio).

/// Get a stable path to a test resource by scanning up to the project root.
Future<File> getProjectFile(String path) async {
  var dir = Directory.current;
  while (!await dir.list().any((entity) => entity.path.endsWith('pubspec.yaml'))) {
    dir = dir.parent;
  }
  return File('${dir.path}/$path');
}

Solution 2

You don't need install a package, just use File from dart:io

I store all my test data files in a "fixtures" folder. This Folder contains a file containing the following code.

import 'dart:async';
import 'dart:io';


Future<File> fixture(String name) async => File('test/fixtures/$name');

In the tests I load my files at beginning of test

final File myTestFile = await fixture(tFileName);

or in mock declarations like in this example

        when(mockImageLocalDataSource.getImage(any))
        .thenAnswer((_) async => Right(await fixture(tFileName)));
Share:
1,338
Matt R
Author by

Matt R

Updated on December 15, 2022

Comments

  • Matt R
    Matt R over 1 year

    I want to read a file with some test data from within a Flutter unit test. Is there a recommended way of doing this? I tried the resource package, but that throws an error:

    dart:isolate                              Isolate.resolvePackageUri
    package:resource/src/resolve.dart 11:20   resolveUri
    package:resource/src/resource.dart 74:21  Resource.readAsString
    
    Unsupported operation: Isolate.resolvePackageUri
    
    • hoangquyy
      hoangquyy over 4 years
      what kind of file you want to read? text file or any file?
    • Benno Richters
      Benno Richters over 4 years
      My (similar) problem is that I use a dart package as a test dependency. That package in turn uses the resource package. Using that in a flutter unit test throws this Unsupported operation error. (The resource is used to read a json file.)
    • hawkbee
      hawkbee over 4 years
      @BennoRichters you should open a new question for your problem
    • Benno Richters
      Benno Richters over 4 years
      @hawkbee yes, you are right.
    • Benno Richters
      Benno Richters over 4 years