Python Mock Library

Buildandteach: Henry Palma
1 min readApr 8, 2023

--

The Python mock library allows you to create mock objects in your unit tests. Mock objects simulate the behavior of real objects in your code without actually performing any of the real work. This can be useful for isolating the code being tested from external dependencies such as network requests or database calls.

Here’s a brief tutorial on using the Python mock library:

  1. Install the mock library using pip: pip install mock

2. Create a mock object using the Mock class from the unittest.mock module:

from unittest.mock import Mock
mock_obj = Mock()

3. Set return values using the return_value attribute:

mock_obj.return_value = 42
result = mock_obj()
print(result) # prints 42

4. Raise exceptions using the side_effect attribute:

mock_obj.side_effect = ValueError("Invalid argument")
try:
result = mock_obj()
except ValueError as e:
print(str(e)) # prints "Invalid argument"

4. Patch objects in your code using the patch decorator:

from unittest.mock import patch

def get_data():
# This function makes a network request to get data
...

def process_data():
data = get_data()
# Process the data
...

@patch('__main__.get_data')
def test_process_data(mock_get_data):
mock_get_data.return_value = 'mock data'
result = process_data()
assert result == expected_result

5. Mock classes using the MagicMock class:

from unittest.mock import MagicMock

class MyClass:
def my_method(self):
return 42

mock_class = MagicMock(spec=MyClass)
mock_class.my_method.return_value = 24
result = mock_class.my_method()
print(result) # prints 24

That’s a brief overview of using the Python mock library. Using mock objects can help you write better tests that are more focused and less likely to fail due to external factors.

--

--