我有以下代碼:如何assertRaises一個特定的異常
def foo(input):
if not input.startswith("prefix"):
raise Exception("input should start with prefix!")
process(input)
現在我想單元測試這個功能;當input
不是以"prefix"
開頭時,它實際上可能會拋出異常。這裏是我的unittest
代碼:
def test_foo_invalud_type(self):
self.assertRaises(Exception, foo, 999)
與這個測試代碼的問題是:它捕獲了異常,但例外的是'int' object has no attribute 'startswith'
,而不是input should start with prefix!
。測試會通過,但這不是一個好的測試。我如何識別兩個例外?
我認爲我誤解了這個問題至少兩次,但我現在對此感到高興...... – jonrsharpe
謝謝。我不得不承認我的問題是一個不好的描述。 – Suanmeiguo