Flutter:测试小部件测试中的异常

xpe*_*dev 8 dart flutter flutter-test

我如何确保 ui(小部件)在 Flutter 中的小部件测试期间抛出异常。这是我的代码不起作用:

expect(
  () => tester.tap(find.byIcon(Icons.send)),
  throwsA(const TypeMatcher<UnrecognizedTermException>()),
);
Run Code Online (Sandbox Code Playgroud)

它失败并出现以下错误

...
Expected: throws <Instance of 'TypeMatcher<UnrecognizedTermException>'>
  Actual: <Closure: () => Future<void>>
   Which: returned a Future that emitted <null>
Run Code Online (Sandbox Code Playgroud)

或者......我是否应该通过查找错误消息等来测试 UI 如何处理异常?

Jon*_*ams 11

要捕获 flutter 测试中引发的异常,请使用WidgetTester.takeException。这将返回框架捕获的最后一个异常。

await tester.tap(find.byIcon(Icons.send));
expect(tester.takeException(), isInstanceOf<UnrecognizedTermException>());
Run Code Online (Sandbox Code Playgroud)

您也不需要throwsA匹配器,因为它不会从方法中抛出。

  • 请注意,这并不适用于所有情况。在某些罕见的情况下,您可能需要覆盖`FlutterError.onError`(并在之后恢复它)。 (4认同)
  • 嘿,异步上下文中引发的异常怎么样?我在测试中很难捕捉到它们。 (2认同)