jeudi 18 juin 2020

Test fails with `flutter test` but passes when debugged from test file

How can I read a file using a relative path when running flutter test?

When running flutter test the File('path/to/file') needs an absolute path but a relative path works when debugging.

I feel like I'm missing something obvious. Using VS Code, I can run a test by starting debug while in one of the test files. By doing so, the test will pass when using a relative path to read a file. However, when I run flutter test from the terminal, the same test fails because it is unable to find the file unless I change it to use an absolute path in which case the test will pass.

This is the line of code in the test that tries to create a model from the json file:

final tUserModel = UserModel.fromJson(json.decode(fixture('user_cached.json')));

The fixture function is imported from a different file and implemented as follows:

import 'dart:io';
String fixture(String name) => File('test/fixtures/$name').readAsStringSync();

When using that relative path I get the following output from terminal:

flutter test
00:03 +3 ~1 -1: loading /home/user/MyApp/test/features/user/data/datasources/user_local_data_source_test.dart [E]                                                                                       
Failed to load "/home/user/MyApp/test/features/user/data/datasources/user_local_data_source_test.dart": Cannot open file, path = 'test/fixtures/user_cached.json' (OS Error: No such file or directory, errno = 2)
dart:io                                                                     _File.readAsStringSync
fixtures/fixture_reader.dart 3:60                                           fixture
features/user/data/datasources/user_local_data_source_test.dart 27:40       main.<fn>
package:test_api                                                            Declarer.group
package:flutter_test/src/test_compat.dart 226:13                            group
features/user/data/datasources/user_local_data_source_test.dart 25:3        main
===== asynchronous gap ===========================
package:test_api                                                            RemoteListener.start
/tmp/flutter_tools.DRSZQD/flutter_test_listener.IPDUJJ/listener.dart 16:25  serializeSuite
/tmp/flutter_tools.DRSZQD/flutter_test_listener.IPDUJJ/listener.dart 43:36  main
flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, 1.19.0-4.1.pre, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.0)
[✓] VS Code (version 1.46.0)
[✓] Connected device (3 available)

• No issues found!
  • How can I get flutter test to work with a relative file path?
  • Is there another way to run all tests from VS Code?

Aucun commentaire:

Enregistrer un commentaire