无法在测试中打开/读取本地文件。引发 FileSystemException:无法打开文件、路径

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

提问人:MXC 提问时间:10/21/2020 更新时间:1/13/2022 访问量:1445

问:

嗨,我正在尝试在我的测试类中读取一个 json 文件。

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”(操作系统错误:没有这样的文件或目录,errno = 2)

这是我的文件结构enter image description here

颤振医生:

[✓] 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

有人可以帮我找到发生了什么吗?

颤振测试

评论


答:

1赞 cyberail 10/21/2020 #1

在测试目录之外获取它,然后:

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

评论

0赞 MXC 10/21/2020
对不起,我希望我的测试文件驻留在测试包中。
0赞 cyberail 10/21/2020
我认为它也会起作用,您的路径将遵循“测试/资源/....”
0赞 MXC 10/21/2020
啊..右。愚蠢的错误。添加成功了。test
0赞 Akbar Pulatov 1/13/2022 #2

您可以尝试而不是从根目录执行命令。来源:https://github.com/flutter/flutter/issues/12999
https://github.com/flutter/flutter/issues/20907
flutter test testflutter test