flutter - 什么是 _TypeError 以及如何处理/测试它?
问题描述
当尝试将错误类型的值分配给 Dart 中的变量时,您会得到一个_TypeError
.
例子:
void main() {
dynamic x = 1;
String y = x;
}
输出:type 'int' is not a subtype of type 'String'
_TypeError 到底是什么?我找不到文档。我无法(特别)抓住它或在单元测试中期望它。
捕捉
以下是迄今为止我能抓住它的唯一方法,但我不想全部抓住。我想使用on ... catch(e)
.,但on _TypeError catch(e)
不起作用,因为_TypeError
未定义。
void main() {
dynamic x = 1;
try {
String y = x;
} catch (e) {
print('catched: ' + e.runtimeType);
print(e.toString());
}
}
输出:
catched: _TypeError
type 'int' is not a subtype of type 'String'
测试
如何在单元测试中期待它?我希望这可以工作,但它没有:
test('throws a _TypeError', () {
dynamic x = 1;
String x;
expect(() => x = y, throwsException);
};
输出:
Expected: throws <Instance of 'Exception'>
Actual: <Closure: () => dynamic>
Which: threw _TypeError:<type 'int' is not a subtype of type 'String'>
解决方案
_TypeError
是一个用于代替 dart 的内部 dart 类TypeError
,因此在大多数情况下,您可以直接使用TypeError
:
dynamic x = 1;
try {
String y = x;
} on TypeError catch (e) {
print('caught: ' + e.runtimeType);
print(e.toString());
}
测试
可悲的是,我不知道有什么方法可以测试 TypeError,我不相信他们为它制作了匹配器,但我可能是错的,但我想你总是可以在演员表本身之前测试
test('throws a _TypeError', () {
dynamic y = 1;
String x;
expect(y, isInstanceOf<String>());
};
如果上述测试失败,那么也会x = y;
推荐阅读
- go - 使用golang使用云触发功能在firebase中进行项目间文件传输
- html - 如何在单击href时翻转展开或折叠文本 - 淘汰赛
- pyopencl - “clGetPlatformIDs 失败:PLATFORM_NOT_FOUND_KHR”在 Windows 上?如何安装驱动程序?
- python-3.x - 长度为 16 的十六进制值的转换不正确
- javascript - Javascript通过对象搜索电话数据并显示在表格中
- php - 从 localhost 调用 Google API
- javascript - 标签之间的 CSS 样式空间
- php - 在 Windows 7 上安装 PEAR
- angular - 如何为动态添加的新输入行设置 ngModel 角度 4+(mat-table)
- ansible - Ansible 拆分返回多个索引