How to Load File For Testing In Flutter??

3 min read
How to Load File For Testing In Flutter
How to Load File For Testing In Flutter

The file can be read from the directory relative to the dart script file. So in this article, we will go through how to Load File For Testing In Flutter.

Are you ready for the same? Let’s start right away!!

How to Load File For Testing In Flutter?

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

test_resources
test_resources

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

So 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 a data.json file to be opened in code under tests with final file = File(dataFilename), then dataFilename will be ‘test_resources/data.json‘.

If a test is executed from Android Studio, test_resources is a folder in the project root. If tests are executed from the command line test_resources is a folder in the test folder.

You can also follow this GitHub link 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();
}

Conclusion:

Thanks for being with us on a Flutter Journey !!!

So in this article, we have been through how to Load File For Testing In Flutter.

Keep Learning !!! Keep Fluttering !!! Stay Connected !!!

Do Let us know if you are still facing doubts about Flutter Development!! We would love to assist you 馃檪

Flutter Agency聽is our portal Platform dedicated to Flutter Technology and聽Flutter Developers. The portal is full of cool resources from Flutter like聽Flutter Widget聽Guide,聽Flutter Projects,聽Code libs聽and etc.

Flutter Agency聽is one of the most popular online portals dedicated to聽Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of聽Flutter.

Leave a Reply