Flutter: how to load file for testing
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.
https://github.com/flutter/flutter/pull/74622
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.
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');
});
}
i created an util because vscode and command line test base path is different
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
Another way is to specify exact test path in command line
$ flutter test test
I encountered this same issue today. My tests passed in my IDE (Android Studio) but failed on CI. I found that the IDE wanted a non-relative path but flutter test
wants a relative path. 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.