gpt4 book ai didi

testing - Flutter:测试 FutureBuilder

转载 作者:行者123 更新时间:2023-12-05 07:29:24 27 4
gpt4 key购买 nike

我想测试一个具有 Future 构建器的函数。函数是:

     Widget loadWidget() {
return new FutureBuilder(
future: getData(),
builder: (BuildContext context, AsyncSnapshot<double> snapshot) {
if (snapshot.hasData) {
double content = snapshot.data;
return new Container(...)
} else {
return new Center(
child: CircularProgressIndicator(),
);

我尝试编写的测试是这样的:

testWidgets("should return a container",
(WidgetTester tester) async {
await tester.pumpWidget(
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Material(
child: Scaffold(
body:loadWidget());
}));

expect(find.byType(Container), findsOneWidget);

getData() 函数似乎有效,所以我认为我的问题可能是我不知道如何处理 AsyncSnapshot。

最佳答案

如果有人遇到这个问题并像我一样寻找答案,我想分享一个可能的解决方案:

Completer<T> completer;
// ...
Widget loadWidget() {
return new FutureBuilder(
// substitute getData() here with the completer's Future
future: completer.future,
builder: (BuildContext context, AsyncSnapshot<double> snapshot) {
if (snapshot.hasData) {
double content = snapshot.data;
return new Container(...)
} else {
return new Center(
child: CircularProgressIndicator(),
);
}
}
);
// ...
testWidgets("should return a container", (WidgetTester tester) async {
completer = Completer<T>(); // initialize Completer here!
await tester.pumpWidget(
StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Material(
child: Scaffold(
body: loadWidget()
)
)
);
}
);
// Interesting part comes here:
// you can provide a Future or some piece of data
// as parameter of the complete method
completer.complete(getData()); // this "completes" (resolves) the future and returns the data you provided
await tester.pump(Duration.zero); // still necessary
expect(find.byType(Container), findsOneWidget); // should succeed now
});

您应该将Future 包装在Completer 中并手动完成Future。看看https://chromium.googlesource.com/external/github.com/flutter/flutter/+/v0.3.3/packages/flutter/test/widgets/async_test.dart .这是我从哪里拿来的。因为我是 Flutter 的新手,所以我真的不知道为什么你必须在 testWidgets 方法中初始化 completer 。可能与 testWidgets 的作用域有关。

关于testing - Flutter:测试 FutureBuilder ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52813572/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com