我想在我的代码中测试异常处理:
def test_get_mails__exception_in_search(self):
with mock.patch('imaplib.IMAP4', autospec=True) as imap_mock:
imap_mock.return_value.create.return_value = ('OK', [''])
imap_mock.return_value.search.side_effect=imap_mock.error
self.get_mails()
但是模拟库提出了:
TypeError: exceptions must be old-style classes or derived from BaseException,
not MagicMock
如何测试我的代码:我希望imaplib.search
举起imaplib.error
答案 0 :(得分:-1)
我找到了解决方案:
with mock.patch('imaplib.IMAP4', autospec=True) as imap_mock:
imap_mock.error=Exception # <---- This is needed, don't ask me why
imap_mock.return_value.create.return_value = ('OK', [''])
imap_mock.return_value.search.side_effect=imap_mock.error
self.get_mails()