无法 open/read 测试中的本地文件。抛出 FileSystemException:无法打开文件、路径

Cannot open/read local files in test. Throws FileSystemException: Cannot open file, path

您好,我正在尝试在测试中读取 json 文件 class。

test(
  'should return a valid model when the JSON is populated with images',
  () async {
    // Given
    File file = new File('resources/image_fixture.json');

    String jsonString = await file.readAsString();

    // When
    final result = Image.fromJson(jsonDecode(jsonString));

    // Then
    expect(result, subject);
  },
);

但是当我读取文件时,出现以下错误

FileSystemException: 无法打开文件,路径 = 'resources/image_fixture.json'(OS 错误:没有这样的文件或目录,errno = 2)

这是我的文件结构

扑博士:

[✓] Flutter (Channel stable, 1.22.1, on Mac OS X 10.15.6 19G2021, locale en-CA)
    • Flutter version 1.22.1 at /Users/asharma/Library/flutter
    • Framework revision f30b7f4db9 (13 days ago), 2020-10-08 10:06:30 -0700
    • Engine revision 75bef9f6c8
    • Dart version 2.10.1

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
    • Android SDK at /Users/asharma/Library/Android/sdk
    • Platform android-30, build-tools 29.0.3
    • ANDROID_HOME = /Users/asharma/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
    ! Some Android licenses not accepted.  To resolve this, run: flutter doctor --android-licenses

[✓] Xcode - develop for iOS and macOS (Xcode 11.6)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.6, Build version 11E708
    • CocoaPods version 1.9.3

[✓] Android Studio (version 4.0)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 49.0.2
    • Dart plugin version 193.7547
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)

[!] IntelliJ IDEA Community Edition (version 2019.3.4)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
    • For information about installing plugins, see
      https://flutter.dev/intellij-setup/#installing-the-plugins

[✓] VS Code (version 1.48.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.12.2

谁能帮我看看这是怎么回事?

在测试目录之外获取它并:

String file = await rootBundle.loadString("/path/to")

您可以从根目录尝试使用 flutter test test 而不是 flutter test 命令。资源: https://github.com/flutter/flutter/issues/12999
https://github.com/flutter/flutter/issues/20907