2014-09-02 37 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

相關問題