【问题标题】:Flutter: Test future builderFlutter:测试未来的构建器
【发布时间】:2019-03-19 16:40:25
【问题描述】:

我想测试一个具有 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。

【问题讨论】:

  • 您遇到了什么错误?
  • 尝试在await tester.pumpWidget(...) 之后调用await tester.pump(); 让FutureBuilder 解析

标签: testing dart flutter future


【解决方案1】:

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

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的作用域有关。

【讨论】:

    猜你喜欢
    • 2019-12-11
    • 2023-01-25
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 2020-06-18
    相关资源
    最近更新 更多