2015-04-21 132 views
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来测试异常并检查是否抛出了异常?
谢谢大家!

回答

2

可以使用测试是否异常被抛出:

test('when the object is in wrong format',() { 
     Map objectMap = {}; 

     expect(() => new MyAwesomeClass.fromMap(objectMap), throws); 
    }); 

传递作为第一个参数的匿名函数提高例外。

+0

哦,我的...当然!这很有道理!非常感谢你! –