【问题标题】:Reading a resource from a file in a Flutter test在 Flutter 测试中从文件中读取资源
【发布时间】:2020-02-23 19:59:49
【问题描述】:

我想从 Flutter 单元测试中读取包含一些测试数据的文件。有推荐的方法吗?我尝试了resource 包,但是会引发错误:

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

【问题讨论】:

  • 你想读什么样的文件?文本文件或任何文件?
  • 我的(类似)问题是我使用 dart 包作为测试依赖项。该包反过来使用资源包。在颤振单元测试中使用它会引发此 Unsupported operation 错误。 (该资源用于读取一个json文件。)
  • @BennoRichters 你应该为你的问题打开一个新问题
  • @hawkbee 是的,你是对的。

标签: flutter resources flutter-test


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您不需要安装包,只需使用来自 dart:io 的文件

    我将所有测试数据文件存储在“fixtures”文件夹中。此文件夹包含一个包含以下代码的文件。

    import 'dart:async';
    import 'dart:io';
    
    
    Future<File> fixture(String name) async => File('test/fixtures/$name');
    

    在测试中我在测试开始时加载我的文件

    final File myTestFile = await fixture(tFileName);
    

    或在本例中的模拟声明中

            when(mockImageLocalDataSource.getImage(any))
            .thenAnswer((_) async => Right(await fixture(tFileName)));
    

    【讨论】:

      猜你喜欢
      • 2014-02-03
      • 2016-06-17
      • 2017-12-02
      • 2021-11-21
      • 1970-01-01
      相关资源
      最近更新 更多