Middle
What is a Mock in testing? What are fixtures?
sobes.tech AI
Answer from AI
Mock in testing is an object or function that simulates the behavior of a real component to isolate the code being tested from external dependencies. Mocks allow you to verify how the code interacts with other parts of the system without calling real services or databases.
Fixtures are pre-prepared data or states used to set up the testing environment. They ensure test repeatability by creating the necessary conditions (e.g., a filled database, files, or objects).
Example of using mock and fixtures in Python with pytest:
import pytest
from unittest.mock import Mock
# Fixture for preparing data
@pytest.fixture
def sample_data():
return {'id': 1, 'name': 'Test'}
# Test using mock
def test_process_data(sample_data):
service = Mock()
service.get_data.return_value = sample_data
result = process(service) # function that calls service.get_data()
assert result == expected_result
service.get_data.assert_called_once()
Thus, mock helps control the behavior of dependencies, and fixtures create a stable testing environment.