简体   繁体   English

Flutter:如何加载文件进行测试

[英]Flutter: how to load file for testing

File can be read from the directory relative to the dart script file, simply as var file = new File('./fixture/contacts.json') .文件可以从相对于 dart 脚本文件的目录中读取,就像var file = new File('./fixture/contacts.json')

However the file cannot be read flutter test running inside IDE.但是,在 IDE 中运行的 flutter 测试无法读取该文件。

Loading as resource (it is not, since I do not want to bundle the test data file in the app) also does not work in test. 作为资源加载(不是,因为我不想在应用程序中捆绑测试数据文件)在测试中也不起作用。

What is a good way to read file in flutter (for both command line test and IDE test)?在 flutter 中读取文件的好方法是什么(对于命令行测试和 IDE 测试)?

Running flutter test is very fast.运行flutter test非常快。 However testing inside Intellij IDE is ver slow, but it can set debug breakpoint and step into and view variables.但是在 Intellij IDE 中进行测试非常慢,但它可以设置调试断点并进入和查看变量。 So both testing is very useful.所以这两种测试都非常有用。

Just had a go at this and it's easier than you might expect.刚刚试了一下,它比你想象的要容易。

First, create a folder that lives in the same directory than your tests are.首先,创建一个与您的测试位于同一目录中的文件夹。 For example, I created a folder called test_resources .例如,我创建了一个名为test_resources的文件夹。

测试资源文件夹结构。

Then, let's say we have the following JSON file for testing purposes.然后,假设我们有以下 JSON 文件用于测试目的。

test_resources/contacts.json test_resources/contacts.json

{
  "contacts": [
    {
      "id": 1,
      "name": "Seth Ladd"
    },
    {
      "id": 2,
      "name": "Eric Seidel"
    }
  ]
}

test/load_file_test.dart测试/load_file_test.dart

We could use it for our test like so:我们可以像这样将它用于我们的测试:

import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';

void main() {
  test('Load a file', () async {
    final file = new File('test_resources/contacts.json');
    final json = jsonDecode(await file.readAsString());
    final contacts = json['contacts'];

    final seth = contacts.first;
    expect(seth['id'], 1);
    expect(seth['name'], 'Seth Ladd');

    final eric = contacts.last;
    expect(eric['id'], 2);
    expect(eric['name'], 'Eric Seidel');
  });
}

I encountered this same issue today.我今天遇到了同样的问题。 My tests passed in my IDE (Android Studio) but failed on CI.我的测试在我的 IDE (Android Studio) 中通过了,但在 CI 上失败了。 I found that the IDE wanted a non-relative path but flutter test wants a relative path.我发现 IDE 想要一个非相对路径,但flutter test想要一个相对路径。 I think this is a bug and I'll be looking for the right place to report it.我认为这是一个错误,我会寻找合适的地方来报告它。 However, I found a crude work around for the meantime.但是,我在此期间找到了一个粗略的解决方法。 Basically, I have a function which tries both ways to specify the file path..基本上,我有一个函数可以尝试两种方式来指定文件路径..

import 'dart:convert';
import 'dart:io';

Future<Map<String, dynamic>> parseRawSample(String filePath,
    [bool relative = true]) async {
  filePath = relative ? "test_data/src/samples/raw/$filePath" : filePath;

  String jsonString;
  try {
    jsonString = await File(filePath).readAsString();
  } catch (e) {
    jsonString = await File("../" + filePath).readAsString();
  }
  return json.decode(jsonString);
}

much of that code is specific to my situation, but I think others could probably adapt this work around for their purposes.大部分代码都特定于我的情况,但我认为其他人可能会根据他们的目的调整这项工作。

i created an util because vscode and command line test base path is different我创建了一个 util 因为 vscode 和命令行测试基本路径不同

https://github.com/terryx/flutter-muscle/blob/master/github_provider/test/utils/test_path.dart https://github.com/terryx/flutter-muscle/blob/master/github_provider/test/utils/test_path.dart

this is how i use it这就是我使用它的方式

https://github.com/terryx/flutter-muscle/blob/master/github_provider/test/services/github_test.dart#L13 https://github.com/terryx/flutter-muscle/blob/master/github_provider/test/services/github_test.dart#L13


Another way is to specify exact test path in command line另一种方法是在命令行中指定确切的测试路径

$ flutter test test

You can just put your test files in two places (I know it is not a good practice to have the same data in two places).您可以将测试文件放在两个地方(我知道在两个地方使用相同的数据不是一个好习惯)。 Let's say I want to have data.json file to be opened in code under tests with final file = File(dataFilename) , then dataFilename will be 'test_resources/data.json'.假设我想让 data.json 文件在测试中用final file = File(dataFilename)在代码中打开,那么 dataFilename 将是'test_resources/data.json'。 If test is executed from Android Studio, test_resources is a folder in project root.如果从 Android Studio 执行测试,则 test_resources 是项目根目录中的文件夹。 If tests are executed from command line test_resources is a folder in test folder.如果从命令行执行测试 test_resources 是 test 文件夹中的一个文件夹。 So placing the file in both places will solve the problem.所以把文件放在两个地方就可以解决问题。

Just copying the solution from Flocbit : https://github.com/flutter/flutter/issues/20907#issuecomment-557634184只需从Flocbit复制解决方案: https : //github.com/flutter/flutter/issues/20907#issuecomment-557634184

String fixture(String name) {
   var dir = Directory.current.path;
   if (dir.endsWith('/test')) {
     dir = dir.replaceAll('/test', '');
   }
   return File('$dir/test/fixtures/$name').readAsStringSync();
}

Works great!效果很好!

The current directory is always the project root in Flutter 2.0 🎉 So you can now read files with the same code on the command line and in the IDE.当前目录始终是 Flutter 2.0 中的项目根目录🎉因此您现在可以在命令行和 IDE 中读取具有相同代码的文件。

https://github.com/flutter/flutter/pull/74622 https://github.com/flutter/flutter/pull/74622

You can use DefaultAssetBundle ,您可以使用DefaultAssetBundle

final response = DefaultAssetBundle.of(context).loadString('assets/file_name.json');最终响应 = DefaultAssetBundle.of(context).loadString('assets/file_name.json');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM