0
0
PyTesttesting~15 mins

Why integration tests verify components together in PyTest - Automation Benefits in Action

Choose your learning style9 modes available
Verify integration of two components: UserService and EmailService
Preconditions (3)
Step 1: Create a UserService instance with a real EmailService instance
Step 2: Call UserService.register_user('testuser@example.com')
Step 3: Check if EmailService sent a welcome email to 'testuser@example.com'
✅ Expected Result: EmailService sends a welcome email to the new user email address
Automation Requirements - pytest
Assertions Needed:
Assert that the email was sent to the correct address
Assert that the email content contains 'Welcome'
Best Practices:
Use fixtures to set up test objects
Avoid mocking the EmailService to test real integration
Use clear and descriptive assertion messages
Automated Solution
PyTest
import pytest

class EmailService:
    def __init__(self):
        self.sent_emails = []

    def send_email(self, to_address: str, content: str):
        self.sent_emails.append({'to': to_address, 'content': content})

class UserService:
    def __init__(self, email_service: EmailService):
        self.email_service = email_service

    def register_user(self, email: str):
        # Imagine user registration logic here
        welcome_message = f"Welcome, {email}!"
        self.email_service.send_email(email, welcome_message)

@pytest.fixture
def email_service():
    return EmailService()

@pytest.fixture
def user_service(email_service):
    return UserService(email_service)

def test_user_registration_sends_welcome_email(user_service, email_service):
    test_email = 'testuser@example.com'
    user_service.register_user(test_email)

    assert len(email_service.sent_emails) == 1, "Expected one email to be sent"
    sent_email = email_service.sent_emails[0]
    assert sent_email['to'] == test_email, f"Email sent to {sent_email['to']} instead of {test_email}"
    assert 'Welcome' in sent_email['content'], "Email content does not contain 'Welcome'"

This test checks that when UserService.register_user is called, it uses the EmailService to send a welcome email.

We create real instances of both services to verify their integration, not mocks, so we test the actual collaboration.

Fixtures set up the services cleanly for reuse.

Assertions check that exactly one email was sent, to the correct address, and that the content includes the word 'Welcome'.

This shows how integration tests verify components working together, not just isolated units.

Common Mistakes - 3 Pitfalls
Mocking EmailService completely and not verifying real email sending
Not asserting the email content or recipient
Using global state or shared EmailService instance across tests
Bonus Challenge

Now add data-driven testing with 3 different user emails to verify welcome emails are sent correctly for each.

Show Hint