rootBundle works great in application but in tests it throws an exception 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/
...
What am I doing wrong?
I found out what's wrong with my test.
There is TestWidgetsFlutterBinding
in flutter_test
package and I should use it instead of WidgetsFlutterBinding
from material
package
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');
});
}
If you defining JSON
file in puspec.yaml
file you have to write full name of your json file like below
assets:
- assets/data.json
In your case, path will be
assets:
- assets/config/prod.json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With