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
來測試異常並檢查是否拋出了異常?
謝謝大家!
哦,我的...當然!這很有道理!非常感謝你! –