在运行flutter test
时如何使用相对路径读取文件?
在运行flutter test
时,File('path/to/file')
需要一个绝对路径,但是在调试时可以使用相对路径。
我觉得我缺少明显的东西。使用VS Code,我可以通过在其中一个测试文件中启动调试来运行测试。这样,使用相对路径读取文件时,测试将通过。但是,当我从终端运行flutter test
时,相同的测试将失败,因为它无法找到文件,除非我将其更改为使用绝对路径,在这种情况下,测试将通过。
这是测试中试图从json文件创建模型的代码行:
final tUserModel = UserModel.fromJson(json.decode(fixture('user_cached.json')));
fixture
函数是从另一个文件导入的,实现如下:
import 'dart:io';
String fixture(String name) => File('test/fixtures/$name').readAsStringSync();
使用该相对路径时,我从终端获得以下输出:
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!
flutter test
使用相对文件路径?答案 0 :(得分:0)
尝试一下。
String fixture(String name) {
var dir = Directory.current.path;
if (dir.endsWith('/test')) {
dir = dir.replaceAll('/test', '');
}
return File('$dir/test/fixtures/$name').readAsStringSync();
}
此问题已在这里提出过几次:https://github.com/flutter/flutter/issues/20907
答案 1 :(得分:0)
这对我有用:
import 'dart:io';
import 'package:path/path.dart';
String fixture(String name) {
final testDirectory = join(
Directory.current.path,
Directory.current.path.endsWith('test') ? '' : 'test',
);
return File('$testDirectory/fixtures/$name').readAsStringSync();
}
感谢:https://github.com/flutter/flutter/issues/20907#issuecomment-466185328