【问题标题】:Flutter: Testing for exceptions in widget testsFlutter:在小部件测试中测试异常
【发布时间】:2019-06-13 04:38:50
【问题描述】:

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

expect(
  () => tester.tap(find.byIcon(Icons.send)),
  throwsA(const TypeMatcher<UnrecognizedTermException>()),
);

失败并出现以下错误

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

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

【问题讨论】:

    标签: dart flutter flutter-test


    【解决方案1】:

    要捕获颤振测试中抛出的异常,请使用WidgetTester.takeException。这将返回框架捕获的最后一个异常。

    await tester.tap(find.byIcon(Icons.send));
    expect(tester.takeException(), isInstanceOf<UnrecognizedTermException>());
    

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

    【讨论】:

    • 实际上expect(tester.takeException(), isInstanceOf&lt;UnrecognizedTermException&gt;()); 工作得很好!谢谢
    • 你让我想到:“...返回框架捕获的最后一个异常”。我宁愿让我的逻辑抓住它以获得更好的设计。这还是很有价值的。不接受 4 分钟后的答案
    • 请注意,这并不适用于所有情况。在极少数情况下,您可能需要覆盖 FlutterError.onError(并在之后恢复)。
    • 该死!。我刚刚遇到了 FlutterError.onError 问题。将发布另一个问题
    • 嘿,在异步上下文中引发的异常呢?我无法在测试中捕捉到它们。
    猜你喜欢
    • 1970-01-01
    • 2019-02-25
    • 2019-10-31
    • 2021-05-09
    • 2023-01-25
    • 2022-06-24
    • 2021-09-22
    • 2020-02-23
    • 2022-07-10
    相关资源
    最近更新 更多