Junior — Middle
How to implement unit testing for a module that sends and receives emails?
sobes.tech AI
Answer from AI
For unit testing a module that sends and receives emails, it is important to isolate the tested code from the real mail system. Mock objects or stubs are used for this purpose.
In Python, you can use the unittest.mock library to replace email sending functions with dummy ones to verify that they are called with the correct parameters.
Example using unittest and mock:
from unittest import TestCase
from unittest.mock import patch
class EmailModule:
def send_email(self, to, subject, body):
# Actual email sending
pass
class TestEmailModule(TestCase):
@patch('path.to.EmailModule.send_email')
def test_send_email(self, mock_send):
email_module = EmailModule()
email_module.send_email('test@example.com', 'Hello', 'Body text')
mock_send.assert_called_once_with('test@example.com', 'Hello', 'Body text')
To receive emails, you can mock methods that fetch messages or use a local SMTP server for testing.