0
0
PyTesttesting~5 mins

Mock and MagicMock in PyTest

Choose your learning style9 modes available
Introduction

Mock and MagicMock help us pretend parts of our program work a certain way. This lets us test other parts without running everything.

When a function calls an external service like a website or database.
When a part of the program is slow or hard to set up for testing.
When you want to check if a function was called correctly without running it.
When you want to replace a complex object with a simple fake version.
When testing code that depends on random or time-based results.
Syntax
PyTest
from unittest.mock import Mock, MagicMock

# Create a simple mock object
mock_obj = Mock()

# Create a MagicMock object with magic methods
magic_mock_obj = MagicMock()

Mock is for general fake objects.

MagicMock includes special methods like __len__ or __getitem__ automatically.

Examples
This mock function always returns 10 when called.
PyTest
from unittest.mock import Mock

mock_func = Mock(return_value=10)
result = mock_func()
print(result)
This MagicMock pretends to be a list with length 5.
PyTest
from unittest.mock import MagicMock

magic_list = MagicMock()
magic_list.__len__.return_value = 5
print(len(magic_list))
Check if the method was called with specific arguments.
PyTest
from unittest.mock import Mock

mock_obj = Mock()
mock_obj.method(3, 4)
mock_obj.method.assert_called_with(3, 4)
Sample Program

This test uses a mock user to check the greet function without needing a real user object.

PyTest
from unittest.mock import Mock

def greet(user):
    return f"Hello, {user.get_name()}!"

# Create a mock user object
mock_user = Mock()
mock_user.get_name.return_value = "Alice"

# Test greet function with mock
result = greet(mock_user)
print(result)

# Check if get_name was called
mock_user.get_name.assert_called_once()
OutputSuccess
Important Notes

Use assert_called_with or assert_called_once to check calls.

MagicMock is useful when your object uses special Python methods.

Mocks do not run real code, so they are fast and safe for testing.

Summary

Mock and MagicMock create fake objects for testing.

Use Mock for general fakes and MagicMock for objects with special methods.

They help test code without running everything or needing real data.