Flutter - Load assets for tests

时间:2018-03-25 19:33:24

标签: flutter flutter-test

Not sure if it's a limitation or something, but below code does not load anything. I have some data driven behaviour that I'd like to test isolated.

class Loader

import 'dart:async';
import 'package:flutter/services.dart' show rootBundle;

class Loader {
  Future<String> load() async{
    return await rootBundle.loadString('assets/json/sketch.json');
  }
}

The test

testWidgets('Should parse load sketch.json', (WidgetTester tester) async {
    var loaderFuture = new Loader();

    Future<String> resultFuture = loaderFuture.load();

    resultFuture.then((value) => print(value))
        .catchError((error) => print(error));

    while(true){};
  });

Future does not return neither success nor error and hangs forever. I know the while(true) locking up the test, but for now I just wanted to see sketch.json printed

Asset location

enter image description here

2 个答案:

答案 0 :(得分:4)

请参阅DefaultAssetBundle的文档,其中描述了如何使用它和AssetBundle提供您自己的资产。

答案 1 :(得分:1)

要在测试中使用rootBundle,请在测试程序开始时使用它:

import 'package:flutter_test/flutter_test.dart';

...
void main() {
  TestWidgetsFlutterBinding.ensureInitialized();