Anton
Anton

Reputation: 2368

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?

Upvotes: 15

Views: 6103

Answers (3)

Kalil BARRY
Kalil BARRY

Reputation: 21

In case you are encountering this problem when building a flutter package, know that by default in pubspec.yaml, the flutter property is set to null (flutter: null), and the indentation of the assets is wrong.

So, you first need to set the flutter property to nothing, like this:
flutter:

Then make sure the assets indentation follows this:

[2 whitespaces or 1 tab]assets:

[4 whitespaces or 2 tabs]- assets/image1.png

[4 whitespaces or 2 tabs]- assets/image2.png

Upvotes: 2

Anton
Anton

Reputation: 2368

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

}

Upvotes: 17

Aamil Silawat
Aamil Silawat

Reputation: 8229

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

Upvotes: 2

Related Questions