My Flutter app has a test folder test
. Inside is another folder called fixtures
.
Here is the fixture_reader.dart
file:
import 'dart:io';
String fixture(String name) => File('test/fixtures/$name').readAsStringSync();
Now I can use the function to read a fixture in a test:
// code ommitted
group('fromJson', () {
test(
'should return a valid model when the JSON number is an integer',
() async {
// arrange
final Map<String, dynamic> jsonMap =
json.decode(fixture('trivia.json'));
// more code
Problem
Now run flutter test
in the command line.
Unfortunately, that gives an error, although all imports are correct:
FileSystemException: Cannot open file, path = 'test/fixtures/trivia.json'
(OS Error: No such file or directory, errno = 2)
dart:io File.readAsStringSync
fixtures/fixture_reader.dart 3:60 fixture
features/number_trivia/data/models/number_trivia_model_test.dart 26:25 main.<fn>.<fn
Why do I have these errors, although the files exist?
FileSystemException: Cannot open file
(OS Error: No such file or directory, errno = 2)
It seems like flutter test
can’t find the file paths! If you use VS Code, the test works fine. But if you use CI/CD, the test will fail.
Solution
Replace file_reader.dart
:
import 'dart:io';
String fixture(String name) {
var dir = Directory.current.path;
if (dir.endsWith('/test')) {
dir = dir.replaceAll('/test', '');
}
return File('$dir/test/fixtures/$name').readAsStringSync();
}