I have a simple function in Django 1.4 that results in a mail being sent. This is put in a try/except, just in case the mailing service might be down (which is an external dependency).
Now, I would like to test this exception. I thought this would be simple, by overriding some email settings (like settings.EMAIL_HOST or settings.EMAIL_BACKEND) but Django test framework does not cause send_mail() to throw an error even if the backend is configured with jibberish…
So the question is: How do I make send_mail() throw an error in my test case?
Thanks!
Answer:
import mock
class MyTestCase(TestCase):
@mock.patch('path.to.your.project.views.send_mail', mock.Mock(side_effect=Exception('Boom!')))
def test_changed_send_mail(self):
I’m not a testing expert, but I think you should use a send_mail mock that raise the exception you want to test.
Probably you could take a look at this stackoverflow question to know more about mocking in Django.