rootBundle在应用程序中运行良好,但在测试中会抛出异常ERROR: Unable to load asset: assets/config/prod.json
configuration.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));
}
}
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');
});
}
pubspec.yaml
...
dev_dependencies:
...
flutter_test:
sdk: flutter
flutter:
assets:
- assets/config/
...
我在做什么错了?
答案 0 :(得分:4)
我发现我的考试出了什么问题。
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');
});
}
答案 1 :(得分:1)
如果您在JSON
文件中定义puspec.yaml
文件,则必须像下面这样写出json文件的全名
assets:
- assets/data.json
在您的情况下,路径将为
assets:
- assets/config/prod.json