2017-06-12 74 views
0

我不知道爲什麼,當我運行測試它總是失敗,Asse田:0 = 1 即使r的結果是1測試SEND_EMAIL不工作

class UserProfileTaskTest(TestCase): 

    def test_send_email(self): 
     subject = 'subject' 
     body = 'body' 
     from_email = '[email protected]' 
     recipient_list = ['[email protected]'] 

     r = send_mail(
      subject=subject, 
      message=body, 
      from_email=from_email, 
      recipient_list=recipient_list 
     ) 

     print(r) 

     self.assertEqual(len(outbox), 1) 
+0

什麼是發件箱? – vZ10

+0

我敢打賭,他們正在像這樣''從django.core.mail導入發件箱'導入它' – Brobin

+0

@Brobin是我導入它就像:)我剛剛開始學習Django我不知道這是一個特殊的屬性。 – mengkheang

回答

0

發件箱是特殊類型屬性,不能直接導入,但當您使用電子郵件後端發送電子郵件時,則mail.outbox將作爲列表並將電子郵件數據保存到發件箱列表中。因此,使用下面的示例爲testmail發送或不發送。

from django.core import mail 
from django.test import TestCase 

class UserProfileTaskTest(TestCase): 
    def test_send_email(self): 
     subject = 'subject' 
     body = 'body' 
     from_email = '[email protected]' 
     recipient_list = ['[email protected]'] 
     mail.send_mail(
      subject=subject, 
      message=body, 
      from_email=from_email, 
      recipient_list=recipient_list 
     ) 
     self.assertEqual(len(mail.outbox), 1) 

當你運行上面的代碼,你有初始mail.outbox = []

但發送電子郵件後,將其保存EmailMessage比如在列表中。

+0

謝謝!它的工作原理就是我沒有閱讀足夠的文檔https://docs.djangoproject.com/en/1.11/topics/testing/tools/#email-services – mengkheang