In software testing, mocking is used to replace parts of the system that the code under test interacts with. Why does this help isolate the code under test?
Think about how external parts can affect test results and why isolating helps.
Mocking replaces external parts like databases or APIs with fake versions. This means tests only check the code's own behavior, not external systems. This isolation makes tests reliable and fast.
What will be the output of this pytest test when the external API call is mocked?
import pytest from unittest.mock import Mock def fetch_data(api_client): return api_client.get_data() def test_fetch_data(): mock_api = Mock() mock_api.get_data.return_value = {'key': 'value'} result = fetch_data(mock_api) assert result == {'key': 'value'} print('Test passed')
Consider what the mock returns and what the assertion checks.
The mock replaces the real API client. It returns the expected dictionary. The assertion matches this, so the test passes and prints 'Test passed'.
Which assertion correctly verifies that the mocked method send_email was called exactly twice during the test?
from unittest.mock import Mock mock_service = Mock() mock_service.send_email() mock_service.send_email()
Check the correct attribute that counts calls on a mock method.
The call_count attribute holds the number of times the mock method was called. It is an integer, so comparing it to 2 with == works.
What error will this pytest test raise when run?
import pytest from unittest.mock import patch def get_user_name(user_id): # Imagine this calls a real database pass def test_get_user_name(): with patch('__main__.get_user_name') as mock_get: mock_get.return_value = 'Alice' result = get_user_name(1) assert result == 'Alice'
Check the patch target string and what it should include.
The patch target must include the module name where get_user_name is defined. Using just 'get_user_name' causes AttributeError because patch cannot find it.
Which pytest fixture setup correctly mocks a database call for all tests in a module, ensuring isolation and cleanup?
Consider scope and autouse to apply mocks for all tests in a module and proper cleanup.
Using scope='module' with autouse=True applies the mock to all tests in the module automatically. Monkeypatch does not require explicit undo if used properly. This setup isolates tests and ensures consistent mocking.