3

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
5
  • what kind of file you want to read? text file or any file? Commented Dec 19, 2019 at 4:18
  • 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.) Commented Dec 19, 2019 at 7:06
  • @BennoRichters you should open a new question for your problem Commented Dec 19, 2019 at 9:18
  • @hawkbee yes, you are right. Commented Dec 20, 2019 at 8:07
  • I did: stackoverflow.com/questions/59421963/… Commented Dec 20, 2019 at 8:23

2 Answers 2

5
+100

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.