0
我使用unittest
函数库在Dart(1.9.3)中编写了一些简单的项目,并进行了单元测试。我在检查构造函数是否抛出错误时遇到了问题。这里的样本代码,我写这个问题的目的:Dart - 构造函数中的异常的单元测试
class MyAwesomeClass {
String theKey;
MyAwesomeClass();
MyAwesomeClass.fromMap(Map someMap) {
if (!someMap.containsKey('the_key')) {
throw new Exception('Invalid object format');
}
theKey = someMap['the key'];
}
}
和这里的单元测试:
test('when the object is in wrong format',() {
Map objectMap = {};
expect(new MyAwesomeClass.fromMap(objectMap), throws);
});
问题是测试失败,以下消息:
Test failed: Caught Exception: Invalid object format
什么我做错了吗?这是unittest
中的错误还是我应该使用try..catch
来测试异常并检查是否抛出了异常?
谢谢大家!
哦,我的...当然!这很有道理!非常感谢你! –