如何編寫僅在函數未引發預期異常的情況下失敗的單元測試?
3 回答

慕萊塢森
TA貢獻1810條經驗 獲得超4個贊
使用unittest模塊中的TestCase.assertRaises(或TestCase.failUnlessRaises),例如:
import mymod
class MyTestCase(unittest.TestCase):
def test1(self):
self.assertRaises(SomeCoolException, mymod.myfunc)

慕蓋茨4494581
TA貢獻1850條經驗 獲得超11個贊
我上一個答案中的代碼可以簡化為:
def test_afunction_throws_exception(self):
self.assertRaises(ExpectedException, afunction)
如果函數接受參數,則將它們傳遞給assertRaises,如下所示:
def test_afunction_throws_exception(self):
self.assertRaises(ExpectedException, afunction, arg1, arg2)
添加回答
舉報
0/150
提交
取消