Flutter:如何加载文件进行测试 [英] Flutter: how to load file for testing

查看:84
本文介绍了Flutter:如何加载文件进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

File can be read from the directory relative to the dart script file, simply as var file = new File('./fixture/contacts.json').

但是,无法在IDE内运行的flutter测试中读取文件.

However the file cannot be read flutter test running inside IDE.

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

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.

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

What is a good way to read file in flutter (for both command line test and IDE test)?

运行flutter test的速度非常快.但是,在Intellij IDE内进行测试的速度很慢,但是它可以设置调试断点并进入并查看变量.因此,这两个测试都非常有用.

Running flutter test is very fast. However testing inside Intellij IDE is ver slow, but it can set debug breakpoint and step into and view variables. So both testing is very useful.

推荐答案

只需尝试一下,它比您预期的要容易.

Just had a go at this and it's easier than you might expect.

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

First, create a folder that lives in the same directory than your tests are. For example, I created a folder called test_resources.

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

Then, let's say we have the following JSON file for testing purposes.

test_resources/contacts.json

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

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

这篇关于Flutter:如何加载文件进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆