4

在我的州级课程中,我宣布了一个未来:

Future<void> _testFuture;

并像这样分配它initState

super.initState();

_testFuture = Future(() async {
      await Future.value(1); //can be any computation
    });

FutureBuilder像这样使用它:

 FutureBuilder(
              future: _testFuture,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done)
                  return Text('Hi');
                else
                  return Center(
                    child: CircularProgressIndicator(),
                  );
              },
            ),

这在正常运行应用程序时工作正常,flutter run但是当我尝试使用小部件测试它时flutter test test/widget_test.dart

void main() {
  testWidgets('Testing', (WidgetTester tester) async {
    // Build our app and trigger a frame.
    await tester.runAsync(() async {
      await tester.pumpWidget(MyApp());
      await tester.pumpAndSettle();
    });
}

它失败了:

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following assertion was thrown while running async test code:
pumpAndSettle timed out

但是,如果我以这种方式分配未来,则相同的测试将毫无问题地通过:

super.initState();

Future<void> testFutures() async {
      await Future.value(1);
    }

_testFuture = testFutures();

两种分配未来的方式有什么区别?

4

2 回答 2

1

如文档pumpAndSettle中所述,默认超时为十分钟。检查您的代码,测试应该运行良好。当我在本地尝试时,初始化任何一种方式都不应该引起任何问题。Future<void>

这是您也可以尝试的示例。完成后应显示文本Future.delayed()。其中之一是在Future<void>上初始化的initState()

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> 

  late Future<void> _testFuture1;

  Future<void> _testFuture2() async {
    // await Future.value(1);
    await Future.delayed(Duration(seconds: 5), () {
      debugPrint('Test 2: \"Hello from the future!\"');
    });
  }

  @override
  void initState() {
    super.initState();
    _testFuture1 = Future(() async {
      // await Future.value(1);
      await Future.delayed(Duration(seconds: 5), () {
        debugPrint('Test 1: \"Hello from the future!\"');
      });
    });
  }

  FutureBuilder _futureBuilder1() {
    return FutureBuilder(
        future: _testFuture1,
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          if (snapshot.connectionState == ConnectionState.done)
            return Text('Test 1 Done!');
          else
            return Center(
              child: CircularProgressIndicator(),
            );
          // return Text('Test 1 Done!');
        });
  }

  FutureBuilder _futureBuilder2() {
    return FutureBuilder(
        future: _testFuture2(),
        builder: (BuildContext context, AsyncSnapshot<dynamic> builder) {
          return Text('Test 2 Done!');
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _futureBuilder1(),
            _futureBuilder2(),
          ],
        ),
      ),
    );
  }
}

这是测试文件

void main() {
  testWidgets('Future test', (WidgetTester tester) async {
    // Build our app and trigger a frame.
    await tester.runAsync(() async{
      await tester.pumpWidget(MyApp());
      await tester.pump(); // both pump() and pumpAndSettle() works fine
    }).then((value) {
      // expect(find.text('Test 1 Done!'), findsOneWidget);
      // expect(find.text('Test 2 Done!'), findsOneWidget);
    });
  });
}

演示

测试

测试

这是我的 Flutter 版本供参考

[✓] Flutter (Channel stable, 2.2.1, on macOS 11.4 20F71 darwin-x64)
    • Flutter version 2.2.1
    • Framework revision 02c026b03c (6 weeks ago), 2021-05-27 12:24:44 -0700
    • Engine revision 0fdb562ac8
    • Dart version 2.13.1
于 2021-07-07T17:47:05.443 回答
0

我遇到了同样的问题,问题是您正在使用 pumpAndSettle 和无限动画(循环进度指示器)-阅读更多https://stackoverflow.com/a/67186625/7138472

于 2021-08-22T10:33:10.060 回答