里面提到
If any of your Django views send email using Django’s email functionality, you probably don’t want to send email each time you run a test using that view. For this reason, Django’s test runner automatically redirects all Django-sent email to a dummy outbox. This lets you test every aspect of sending email – from the number of messages sent to the contents of each message – without actually sending the messages.
The test runner accomplishes this by transparently replacing the normal email backend with a testing backend.
(Don’t worry – this has no effect on any other email senders outside of Django, such as your machine’s mail server, if you’re running one.)
意思是说每次运行测试都会发送邮件会不利于测试,所以在测试中会自动转换发送邮件到一个虚拟的outbox里,用来测试email的情况,并没有发送真正的邮件
那要怎么测试呢?
答案是:
django.core.mail.outbox
在测试环境下,每一封发出的邮件都会被保存为django.core.mail.outbox
例子:
from django.core import mail from django.test import TestCase class EmailTest(TestCase): def test_send_email(self): # Send message. mail.send_mail('Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False) # Test that one message has been sent. self.assertEqual(len(mail.outbox), 1) # Verify that the subject of the first message is correct. self.assertEqual(mail.outbox[0].subject, 'Subject here')