Reputation: 10503
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
Upvotes: 3
Views: 2486
Reputation: 10503
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');
}
Upvotes: 5
Reputation: 1611
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)));
Upvotes: 1