Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to load assets in flutter tests

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?

like image 478
Anton Avatar asked Mar 13 '20 13:03

Anton


2 Answers

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');
  });

}
like image 76
Anton Avatar answered Sep 28 '22 08:09

Anton


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
like image 32
A R Avatar answered Sep 28 '22 09:09

A R