谁能告诉我如何在小部件测试期间实现覆盖Flutter 错误,以便我可以判断我自己的自定义错误.

我在网上看到过提到这一点的片段,但我的所有实现都失败了

void main() {

  testWidgets('throws an error when scanning unknown term types', (WidgetTester tester) async {
    await tester.pumpWidget(injectTestWidget(new ItemScanScreen()));

    await tester.enterText(find.byKey(new Key('term')), '');
    await tester.tap(find.byIcon(Icons.send));
    await tester.pump();

    expect(
      tester.takeException(),
      isInstanceOf<UnrecognizedTermException>(),
      reason: 'should have thrown an UnrecognizedTermException error but didn\'t',
    );
  });
}

上面的代码失败,并显示以下消息,尽管它看起来实际上"捕获"了我的错误:

The following UnrecognizedTermException was thrown running a test:
Instance of 'UnrecognizedTermException'
...

我读到你可以做下面的代码片段,但它没有看到如何/在哪里实现它:

final errorHandled = expectAsync0((){});

FlutterError.onError = (errorDetails) {
  // handle error
  errorHandled();
});

推荐答案

这是为测试而设计的.我切换到try/catch中的包装逻辑,然后对"错误消息文本"当前概念运行Expect().例如:

try {
   throw new UnrecognizedTermException();
 } catch (e) {
   setState(() => _status = e.errMsg());
}

// then in my test
expect(find.text('Could not determine the type of item you scanned'), findsOneWidget);

Dart相关问答推荐

为什么 Dart 的编译器认为代码可能为空,而代码保证它不能为空?

Dart 中的const关键字放置有什么不同?

是否从 Dart 中删除了interface关键字?

我可以动态应用 Dart 的字符串插值吗?

如何在 Dart 单元测试中模拟或验证打印调用?

Dart VM 的性能与 Node.js 相比如何?

访问用户环境变量

如何在 Dart 中获取数字的长度?

设置Dart中非常量的默认值

将Flutter的 PageView 与屏幕左侧对齐

Flutter:如何获取assets目录中所有图像的名称列表?

如何在 Dart 中将字符串转换为 utf8?

Dart:将十进制转换为十六进制

如何将条目添加到列表中的特定索引?

如何在 Ubuntu 网络服务器上为 Dart 安装 pub(命令行使用)

如何使异步 Dart 调用同步?

你如何在 Dart 中打印美元符号 $

在 DART 中创建泛型类型的实例

如何在 Dart 中将 double 转换为 int?

你如何在 Dart 中构建一个单例?