0
0
PyTesttesting~5 mins

Why mocking isolates code under test in PyTest

Choose your learning style9 modes available
Introduction

Mocking helps test one part of code by pretending other parts work correctly. This way, you focus only on what you want to check.

When a function depends on a slow database or network call.
When a part of code uses an external service you cannot control.
When you want to test error handling without causing real errors.
When the real code changes data and you want to avoid side effects.
When you want to test a small piece of code without running the whole system.
Syntax
PyTest
from unittest.mock import Mock

mock_object = Mock()
mock_object.method.return_value = expected_value

result = code_under_test(mock_object)
assert result == expected_result

Use Mock() to create a fake object.

Set return values or side effects to control behavior.

Examples
This example mocks an API call to return fixed data.
PyTest
from unittest.mock import Mock

mock_api = Mock()
mock_api.get_data.return_value = {'id': 1, 'name': 'Test'}

response = mock_api.get_data()
assert response['name'] == 'Test'
This example mocks a database save method to raise an error for testing error handling.
PyTest
from unittest.mock import Mock

mock_db = Mock()
mock_db.save.side_effect = Exception('DB error')

try:
    mock_db.save()
except Exception as e:
    assert str(e) == 'DB error'
Sample Program

This test uses a mock API client to isolate and test the fetch_user_name function without calling a real API.

PyTest
from unittest.mock import Mock

def fetch_user_name(api_client, user_id):
    user = api_client.get_user(user_id)
    return user['name']

# Create a mock API client
mock_api = Mock()
mock_api.get_user.return_value = {'id': 42, 'name': 'Alice'}

# Test fetch_user_name with the mock
result = fetch_user_name(mock_api, 42)
assert result == 'Alice'
print('Test passed')
OutputSuccess
Important Notes

Mocking avoids slow or unreliable external calls during tests.

It helps test only the code you want, making tests simpler and faster.

Remember to set expected return values or side effects on mocks.

Summary

Mocking replaces real parts with fake ones to isolate code under test.

This makes tests faster, more reliable, and focused.

Use mocks to control dependencies and test different scenarios easily.