在 Flutter 测试中从文件中读取资源

Mat*_*t R 3 resources flutter flutter-test

我想从 Flutter 单元测试中读取包含一些测试数据的文件。有推荐的方法吗?我尝试了资源包,但抛出错误:

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
Run Code Online (Sandbox Code Playgroud)

Mat*_*t R 5

最后,我使用了以下技巧(唉,我不记得在哪里看到它建议正确归属它)来扫描文件系统树以找到项目根目录。这样,无论测试是从哪个目录执行的,测试都可以找到数据(否则我的测试在命令行上通过,但在 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');
}

Run Code Online (Sandbox Code Playgroud)