Mock
Мок
A test can replace a real dependency, such as an email service, with a mock. The mock lets the test check whether the code called that dependency and what arguments it passed.
Also known as: стаб, stub, фейк, test double
What is a mock?
A mock is a stand-in for a dependency that lets a test verify how the code interacts with it. Suppose checkout must send one receipt after a successful payment. A unit test doesn't need to deliver an email. It can supply a mock mailer and check that checkout asked it to send exactly one receipt to the right address.
How it works
Give the code under test a mock in place of the real dependency, often by passing it into a function or constructor. Run the scenario, then check the relevant calls. Some frameworks let you set expectations before running the code; others let you assert against a call history afterward. Typical checks cover the method, its arguments, and the number of calls. Check their order only if it matters to the behavior—for example, if a receipt must not be requested before payment succeeds.
Example in Python
from unittest.mock import Mock
def send_receipt(mailer, email, order_id):
mailer.send(email, f'Receipt for order {order_id}')
def test_send_receipt():
mailer = Mock()
send_receipt(mailer, 'buyer@example.com', 42)
mailer.send.assert_called_once_with(
'buyer@example.com', 'Receipt for order 42'
)
This test verifies the request to send an email, not that an email arrived. Python's plain Mock also doesn't enforce the real mailer's interface. An autospecced mock can catch some interface mismatches, such as a wrong method signature, but it won't tell you whether the real provider accepts or delivers the message. That needs a separate integration check.
Mock, stub, or fake?
Test double is the umbrella term. A stub provides a preset answer, such as a declined payment, so the test can exercise a particular branch. A fake has a working but simplified implementation, such as an in-memory order repository. A mock verifies an interaction. These are roles, not necessarily different classes: a Python Mock configured to return a value is acting as a stub if the test never checks how it was called.
When to use one
Mock an interaction when it is itself part of the requirement, such as not sending a receipt after a declined payment. If you only care about a calculation's result, assert the result rather than the sequence of helper calls. Tests that pin down internal calls can fail during a harmless refactor. In an interview, expect to explain both what your mock-based test proves and what you'd still test with the real dependency.