Ant*_*ton 4 unit-testing assets flutter
rootBundle 在应用程序中运行良好,但在测试中它抛出异常 ERROR: Unable to load asset: assets/config/prod.json
配置.dart
import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;
class Configuration {
final Map<String, String> _config = {};
String get(String key) {
return _config[key];
}
Future<void> load() async {
_config.clear();
final configString = await rootBundle.loadString('assets/config/prod.json');
final configJson = jsonDecode(configString) as Map<String, dynamic>;
_config.addAll(Map.castFrom<String, dynamic, String, String>(configJson));
}
}
Run Code Online (Sandbox Code Playgroud)
configuration_test.dart
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/data/models/configuration.dart';
void main() {
setUpAll(() {
WidgetsFlutterBinding.ensureInitialized();
});
test('should load configuration', () async {
final config = Configuration();
await config.load();
expect(config.get('client_id'), 'client_id');
});
}
Run Code Online (Sandbox Code Playgroud)
pubspec.yaml
...
dev_dependencies:
...
flutter_test:
sdk: flutter
flutter:
assets:
- assets/config/
...
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
我发现我的测试有什么问题。有TestWidgetsFlutterBinding在flutter_test包中,我应该使用它而不是WidgetsFlutterBinding从material包中
configuration_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/data/models/configuration.dart';
void main() {
setUpAll(() {
TestWidgetsFlutterBinding.ensureInitialized();
});
test('should load configuration', () async {
final config = Configuration();
await config.load();
expect(config.get('client_id'), 'client_id');
});
}
Run Code Online (Sandbox Code Playgroud)
如果您在文件中定义JSON文件,puspec.yaml则必须编写 json 文件的全名,如下所示
assets:
- assets/data.json
Run Code Online (Sandbox Code Playgroud)
在你的情况下,路径将是
assets:
- assets/config/prod.json
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1926 次 |
| 最近记录: |