首页 > 解决方案 > 什么是 _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'>

标签: flutterunit-testingdarterror-handlingtypeerror

解决方案


_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;


推荐阅读