我有这样的代码:
def extract(data):
if len(data) == 3:
a = 3
else:
component = data.split("-")
if len(component) == 3:
a,b,c = component
else:
raise globals.myException("data1", "Incorrect format", data)
return a,b,c
这是一个简化的。我想模拟异常类 globals.myException。我正在这样做:
def test_extract_data_throws_exception(self):
with patch('globals.myException') as mock:
mock.__init__("data1", "Incorrect format", "")
with self.assertRaises(myException):
self.assertEqual(extract(""), (""))
而且我总是收到错误:“TypeError:异常必须是旧式类或派生自 BaseException,而不是 MagicMock”
编辑:正如@Aaron Digulla 建议的那样,猴子补丁是正确的解决方案。我发布解决方案以帮助他人。
def test_extract_data_throws_exception(self):
#monkey patching
class ReplaceClass(myException):
def __init__(self, module, message, detail = u''):
pass
globals.myException = ReplaceClass
with self.assertRaises(myException:
self.assertEqual(extract(""), (""))