在对返回不同类型对象的函数进行单元测试时,我需要检查返回对象的类型是否与预期相同。因此,我需要在变量内传递多个类。然后我需要将此变量与is
运算符一起使用来检查类型。
final string = String;
assert('foo' is string);
Run Code Online (Sandbox Code Playgroud)
但我越来越
error: The name 'string' isn't a type and can't be used in an 'is' expression.
Run Code Online (Sandbox Code Playgroud)
我在某处读到一个名为的库Dart:mirrors
可以解决这个问题,但我还没有看到一个实际的例子。
TSR*_*TSR -1
我找到了答案。创建我想要断言的类型的实例,然后使用runtimeType
属性的技巧。
如果从a.dart调用一个类,User
并且从b.dart调用另一个类User
,则runtimeType将不一样
final string = 'anything'.runtimeType;
assert('foo'.runtimeType is string);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1964 次 |
最近记录: |