Junior — Middle
What is the difference between mock objects and fixtures in pytest and how to use them in tests?
sobes.tech AI
Answer from AI
In pytest, fixtures and mock objects serve different purposes, although both assist in testing.
Fixtures are functions that prepare and provide test data or environment. They can create objects, set up state, open connections, etc. Fixtures are convenient for reusing setup code across different tests.
Example of a fixture:
import pytest
@pytest.fixture
def sample_data():
return {'key': 'value'}
def test_example(sample_data):
assert sample_data['key'] == 'value'
Mock objects are dummy objects that imitate the behavior of real dependencies, allowing control over their behavior and verifying calls. Mocks are useful when isolating the code under test from external services or complex components.
Example of using mock:
from unittest.mock import Mock
def test_api_call():
mock_service = Mock()
mock_service.get_data.return_value = {'id': 1}
result = some_function_using_service(mock_service)
assert result == expected_result
mock_service.get_data.assert_called_once()
Summary:
- Fixtures create and provide test data or environment.
- Mocks replace real objects to control behavior and verify interactions.
Usually, fixtures can return mocks, combining both approaches.