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

Flutter: how to load file for testing

文件可以从dart脚本文件的相对目录中读取,简单来说就是var file = new File('./fixture/contacts.json').

但是IDE里面的flutter test 运行无法读取文件。

(不是,因为我不想在应用程序中捆绑测试数据文件)在测试中也不起作用。

在 flutter 中读取文件的好方法是什么(对于命令行测试和 IDE 测试)?

运行 flutter test 非常快。然而在 Intellij IDE 中测试非常慢,但它可以设置调试断点并进入并查看变量。所以这两个测试都非常有用。

刚刚试了一下,它比您想象的要容易。

首先,创建一个与您的测试位于同一目录中的文件夹。例如,我创建了一个名为 test_resources.

的文件夹

然后,假设我们有以下 JSON 文件用于测试目的。

test_resources/contacts.json

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

test/load_file_test.dart

我们可以像这样将它用于我们的测试:

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');
  });
}

您可以使用DefaultAssetBundle,

最终响应 = DefaultAssetBundle.of(上下文).loadString('assets/file_name.json');

我今天遇到了同样的问题。我的测试在 IDE(Android Studio)中通过,但在 CI 中失败。我发现 IDE 想要 non-relative 路径,但 flutter test 想要相对路径。我认为这是一个错误,我会寻找合适的地方报告它。但是,我同时找到了一个粗略的解决方法。基本上,我有一个函数尝试两种方式来指定文件路径..

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);
}

大部分代码都是针对我的情况,但我认为其他人可能会根据他们的目的调整此工作。

我创建了一个实用程序,因为 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/services/github_test.dart#L13


另一种方法是在命令行中指定准确的测试路径

$ flutter test test

你可以把你的测试文件放在两个地方(我知道在两个地方有相同的数据不是一个好习惯)。假设我想在测试代码中使用 final file = File(dataFilename) 打开 data.json 文件,那么数据文件名将为 'test_resources/data.json'。如果测试是从 Android Studio 执行的,test_resources 是项目根目录中的一个文件夹。如果测试是从命令行执行的,test_resources 是测试文件夹中的一个文件夹。所以把文件放在这两个地方就可以解决问题了。

只是从 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();
}

效果很好!

当前目录在Flutter 2.0中始终为项目根目录 因此,您现在可以在命令行和 IDE.

中使用相同的代码读取文件

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

一个简单的解决方案是

import 'dart:io';

String fixture(String name) => File('test/fixtures/$name').readAsStringSync();

test 文件夹与 lib 文件夹在同一级别,您可以这样访问夹具: String fileContent = fixture('contacts.json')

之后通常将 fileContent 转换为 Map 对象 jsonDecodedart:convert 然后将此转换后的对象映射到您想要的模型,该模型通常具有 myModel.fromJson(Map onvertedJson)方法。

您可以根据 JSON 响应 json to dart android studio plugin or use online converter tools like this online JSON converter

生成模型