Reading a resource from a file in a Flutter test
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)));
Matt R
Updated on December 15, 2022Comments
-
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 over 4 yearswhat kind of file you want to read? text file or any file?
-
Benno Richters over 4 yearsMy (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 over 4 years@BennoRichters you should open a new question for your problem
-
Benno Richters over 4 years@hawkbee yes, you are right.
-
Benno Richters over 4 years
-