2014-09-01 21 views

回答

1

AssertRaises(一)可以測試所有EXCE你從代碼中提出的。

的語法使用assertRaises是:

assertRaises(CustomException, Function that throws the exception, Parameters for function(In case of multiple params, they will be comma separated.)) 

它是如何工作的:

當遇到assertRaises,PyUnit中執行裏面提到的功能,嘗試,除非包含CustomException的except塊的塊。如果正確處理異常,測試通過,否則失敗。

有關assertRaises的更多信息,請訪問How to properly use unit-testing's assertRaises() with NoneType objects?

0

如果引發異常的模塊和您的測試代碼引用了不同名稱空間中的異常,則會發生這種情況。

因此,舉例來說,如果您有:

# code_to_be_tested.py 

from module_with_exception import * # including CustomException 

... 

raise CustomException() 

# test_code.py 

import module_with_exception.CustomException as CE 

... 

with assertRaises(CE) ... 

這是因爲這兩個文件實際上最終指向不同的類/對象。


所以,解決這個方法有兩種:

  • 指他們以同樣的方式,如果可能的話
  • ,如果你不喜歡的東西from blah import *,抓住從測試模塊異常本身,因爲這是它的提高(即from code_to_be_tested import CustomException
相關問題