简体   繁体   中英

Unable to load asset in flutter test using rootBundle

I created a Loader class that loads a text asset containing names. It works fine when used in the program but I get the error Unable to load asset: assets/texts/names.txt when I try to use it in a test.

my directory structure is

|- assets  
   |- texts  
      |- names.txt  
|- load_text  
   |- load_text.dart  
   |- loader.dart  
|- test  
   |- asset_test.dart

my pubspec.yaml has - assets/texts/names.txt included.

loader.dart

class Loader{
   Future<String> loadNames() async{
    return await rootBundle.loadString('assets/texts/names.txt');
   }
}

load_text.dart

class ValidationApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
    title: 'userDetApp',
    home: Scaffold(
    appBar: AppBar(title: Text('Load names'),),
    body: Column(
      children: <Widget>[
        RaisedButton(
          child: Text('Click'),
          onPressed: (){
            Loader().loadNames().then((names){
                print(names);
            });
          },
        )
      ],
    )
  ),
);

} }

asset_test.dart

void main(){
   test('Should load asset', () async{
       String names = await new Loader().loadNames();
       expect(names, 'John, Peter, Mary');
   });
}

Everything works fine except for the test that fails to find the asset. Need help. Thanks!

I encountered similar issues accessing file resources using flutter driver for integration tests. What I did as a workaround was load the resources needed to an API and parse the JSON response directly, instead of accessing the resources from the assets folder.

Here's a sample that you can try out. This uses https://jsonplaceholder.typicode.com as its endpoint sample.

test('Test http', () async {
    final file = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
  final json = jsonDecode(file.body.toString());
  print('json contents: $json');
  print('userId: ${json['userId']}');
  final userId = json['userId'];
  expect(userId, 1);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM