Reading a resource from a file in a Flutter test


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


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');

Answered By – Matt R

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.