其實你需要啓動模擬,以便side_effect
開始,例如以下:
class Test(unittest.TestCase):
def test(self):
mock = m.Mock()
mock.side_effect = Exception("Big badaboum")
self.assertRaises(Exception, mock)
self.assertRaises
可以採取可調用的第二個參數,使其等同於:
class Test(unittest.TestCase):
def test(self):
mock = m.Mock()
mock.side_effect = Exception("Big badaboum")
with self.assertRaises(Exception):
mock()
如果你想在補丁測試中使用它,你可以執行以下操作:
import unittest.mock as m
import unittest
def raise_error():
try:
print("Hello") #placeholder for the try clause
except Exception as e:
print(e) #placeholder for the exceptclause
class Test(unittest.TestCase):
@m.patch("__main__.raise_error", side_effect=Exception("Big badaboum")) #replace __main__ by the name of the module with your function
def test(self, mock):
with self.assertRaises(Exception):
mock()
unittest.main()
編輯:並測試一個錯誤的加薪內的除塊,你需要模擬你寫try塊內的函數調用,例如:
import unittest.mock as m
import unittest
def do_sthing():
print("Hello")
def raise_error():
try:
do_sthing() #this call can be mocked to raise an IOError
except IOError as e:
print(e.strerror)
raise ValueError("Another one")
class Test(unittest.TestCase):
def test(self):
with m.patch("__main__.do_sthing", side_effect=IOError("IOError")):
self.assertRaises(ValueError, raise_error)
unittest.main()
您可以使用修飾語法以及(只是把上面的測試重寫了一些CPU週期):
class Test(unittest.TestCase):
@m.patch("__main__.do_sthing",side_effect=IOError("IOError"))
def test(self, mock):
self.assertRaises(ValueError, raise_error)
您好asettouf,感謝您的answr。我試過了,儘管看起來測試已通過,但代碼覆蓋率顯示,try和except塊都未經過測試。我想我缺少的東西.. – Joe
@Giuseppe「代碼覆蓋」,哪種?你也有測試什麼時候沒有引發異常嗎? – Adonis
到目前爲止,我在異常不會引發時進行測試:self.assertRaises(IOError,myClass.myFunction)。它的工作原理,但它當然是失敗的,因爲它是假的,沒有例外。現在我被要求有一個完整的覆蓋範圍,並測試除了塊。爲此,我需要模擬IOError – Joe