什么是 _TypeError 以及如何 handle/test 它?

What is _TypeError and how to handle/test it?

在 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是一个内部飞镖class用来代替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;