Create a Mock Email Service
Intermediate · Write the code · from Python Mocking and Fixtures: Test Code with External Dependencies
From the lesson: Python Mocking and Fixtures: Test Code with External Dependencies
Before car companies test a new vehicle in a real crash, they use a crash test dummy. The dummy is a stand-in for a real person - it behaves similarly enough to be useful, but nobody gets hurt.
Read the lessonCreate a MockEmailService class with a send_email(to, subject, body) method that stores sent emails in a list called sent_emails (as tuples). Then write a notify_user function that uses the service to send a welcome email. Test that calling notify_user results in exactly one email with the correct recipient. Print Mock email test passed! at the end.
# Create the MockEmailService class
# Write notify_user(service, username)
# It should send an email to "<username>@example.com"
# with subject "Welcome!" and body "Thanks for joining!"
# Test it
More Mocking exercises
- Predict the Mock BehaviorIntermediate
- Mock the ClockAdvanced
- Build a Test FixtureAdvanced
- Fix the Broken MockAdvanced