如何测试异步异常?

How to test async exception?

我想知道如何测试小部件是否抛出异步异常。

在小部件的 initState 上创建的异常:

  Future<void> _asyncError() async =>
      Future.delayed(Duration(microseconds: 1), () => throw FaultRoots.async);

没有检测到异常然后抛出异常的测试:

            try {
              await tester.pumpWidget(widget);
              await tester.pumpAndSettle();

  
              expect(tester.takeException(), isNotNull);
              expect(tester.takeException().toString(), contains(p.route));
            } catch (ex) {
              print(ex.toString());
            }

异常:

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following message was thrown running a test:
/fault/async

When the exception was thrown, this was the stack:
#0      _FaultPageState._asyncError.<anonymous closure> (package:flutter_firebase_hello/pages/fault_page.dart:26:55)
#8      FakeTimer._fire (package:fake_async/fake_async.dart:316:16)
#9      FakeAsync._fireTimersWhile (package:fake_async/fake_async.dart:240:13)
#10     FakeAsync.elapse (package:fake_async/fake_async.dart:137:5)
#11     AutomatedTestWidgetsFlutterBinding.pump.<anonymous closure> (package:flutter_test/src/binding.dart:965:28)
#14     TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:72:41)
#15     AutomatedTestWidgetsFlutterBinding.pump (package:flutter_test/src/binding.dart:961:27)
#16     WidgetTester.pumpAndSettle.<anonymous closure> (package:flutter_test/src/widget_tester.dart:640:23)
<asynchronous suspension>
<asynchronous suspension>
(elided 10 frames from dart:async and package:stack_trace)

runZonedGuarded 可以捕获异步异常:

            await runZonedGuarded(() async {
              await tester.pumpWidget(makeTestable(widget));
              await tester.pumpAndSettle();
            }, (error, stack) {
              ... error validation ...
            });