简体   繁体   English

在颤振单元测试中访问 rootBundle

[英]accessing rootBundle in flutter unit test

I am writing a unit test in my flutter app, seems I can't read json from assets in tests, but it works if I run app,我正在我的 flutter 应用程序中编写单元测试,似乎我无法从测试中的资产中读取 json,但是如果我运行应用程序,它就可以工作,

I use code below to read json as string :我使用下面的代码将 json 读取为字符串:

var jsonString = await rootBundle.loadString("assets/student_list.json");

How can I access jsons assets in tests?如何在测试中访问 jsons 资产?

Add this line as the first to be executed in your test and it will work and load the assets:将此行添加为测试中要执行的第一行,它将工作并加载资产:

TestWidgetsFlutterBinding.ensureInitialized();

It will initialise everything before running your code and the assets will be accessible at that point.它将在运行您的代码之前初始化所有内容,并且此时可以访问资产。

You can use DefaultAssetBundle to access assets in tests. 您可以使用DefaultAssetBundle访问测试中的资产。 Check out the documentation. 查看文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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