其实你需要启动模拟,以便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