Chapter 19. Using Mocks to Test External Dependencies or Reduce Duplication
In
this chapter we’ll start testing the parts of our code that send emails.
In the FT, you saw that Django gives us a way of retrieving any emails it
sends by using the mail.outbox attribute. But
in this chapter, I want
to demonstrate a very important testing technique called mocking, so for
the purpose of these unit tests, we’ll pretend that this nice Django shortcut
doesn’t exist.
Note
Am I telling you not to use Django’s mail.outbox? No; use it, it’s a
neat shortcut. But
I want to teach mocks because they’re a useful
general-purpose tool for unit testing external dependencies. You
may not always be using Django! And even if you are, you may not
be sending email—any interaction with a third-party API is a good
candidate for testing with mocks.
Before We Start: Getting the Basic Plumbing In
Let’s just get a basic view and URL set up first. We can do so with a simple test that our new URL for sending the login email should eventually redirect back to the home page:
accounts/tests/test_views.py
fromdjango.testimportTestCaseclassSendLoginEmailViewTest(TestCase):deftest_redirects_to_home_page(self):response=self.client.post('/accounts/send_login_email',data={'email':'edith@example.com'})self.assertRedirects(response,'/')
Wire up the include in superlists/urls.py, plus the url in
accounts/urls.py, and get the test passing with something a bit like this:
accounts/views.py
fromdjango.core.mail ...