2014-09-02 64 views
1

我要测试的异常处理在我的代码:类型错误:例外必须是老式类或BaseException衍生,不MagicMock

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

包括* full *回溯会让你更容易回答超出*不问我为什么*。我可以告诉你为什么。 – 2014-09-02 14:01:18

回答

-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() 
+0

听起来像你真的应该使用'imap_mock.return_value.search.side_effect = Exception'然后。 – 2014-09-02 14:03:07

+0

或者更确切地说,'imap_mock.return_value.search.side_effect = Exception('Some message')'。 – 2014-09-02 14:21:46