Search code examples
testingintellij-ideareadfileflutter

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').

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.

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

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.


Solution

  • 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 folder structure.

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