我需要測試我的python代碼是否有異常,但我似乎無法獲得正確的語句來運行。
當我測試的生產代碼,我可以看到異常被拋出,但是當我在我的單元測試文件來測試這個例外,我得到這個:使用pyunit測試Python中的異常
testincorrectparam (unittestearnings.TestEarningsArgs)
should raise error when param not an integer ... "3v" is not a valid argument. i should be an integer
ERROR
我通過類似的問題對SO讀,但我只是不「T設法找到我的問題一個滿意的答案..
生產代碼如下所示:
class Earnings():
def printd(i=0):
try:
i = int(i)
except Exception:
print('"' + i + '"' + " is not a valid argument. i should be an integer")
sys.exit(0)
而且單元測試代碼是這樣的:
from earnings import Earnings
import unittest
class TestEarningsArgs(unittest.TestCase):
def testincorrectparam(self):
'''should raise error when param not an integer'''
e = Earnings()
value = "3v"
self.assertRaises(Exception, e.printd(i=value))
if __name__ == "__main__":
unittest.main()
真的很感謝任何幫助。
請注意,'printd()'不採取「參數」n amed參數,所以你的測試或代碼在這裏也是不正確的。 – geoffspear 2012-08-10 15:08:43
@Wooble感謝您發現這一點,代碼現在一致。然而,我的問題仍然有效。乾杯 – jule64 2012-08-10 17:25:24