Python · The language, not just syntax

How do you mock dependencies without making tests brittle?

Mediummockingunittest.mocktestingUpdated Oct 2026
Quiz this track

Short answer

Patch the name where it is looked up, not where it is defined, use autospec to keep signatures honest, and prefer fakes or injected collaborators over patching deep internals.

unittest.mock replaces an attribute for the duration of a test. The most common mistake is patching the defining module instead of the module under test, which leaves the code still bound to the real object.

python
from unittest.mock import patch

def test_charge_retries(monkeypatch):
    calls = []

    class FakeGateway:
        def charge(self, amount):
            calls.append(amount)
            return {"status": "ok"}

    service = PaymentService(gateway=FakeGateway())
    result = service.charge(500)

    assert result["status"] == "ok"
    assert calls == [500]
Injecting a fake collaborator tests behaviour without patching internals. The fake is small and obvious.

Mocking rules

  • Patch where the object is used: patch the module under test, not the source module
  • Use autospec=True so wrong argument signatures fail in the test
  • Use side_effect to raise exceptions or return a sequence
  • Use AsyncMock for async callables, never a plain MagicMock

Over-mocking couples tests to implementation. If a test asserts every internal call, a harmless refactor breaks it while a real bug can still pass. Prefer real value objects, small fakes and dependency injection, and reserve mocks for external systems such as networks, clocks and payment providers.

A mock assertion can prove a method was called but not that the resulting behaviour is correct. Combine interaction checks with outcome assertions where possible.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why must you patch where the name is looked up?
  2. 2What does autospec=True prevent?
  3. 3When is a fake better than a mock?
  4. 4How do you test an async dependency?

Say it in the interview

I patch the name where it is used, because Python resolves the reference in the module under test at call time. I use autospec so bad signatures fail, side_effect for errors, and AsyncMock for async code. Mostly I prefer injecting a small fake over patching internals, because over-mocked tests break on refactors without catching real bugs. I keep mocks at the boundary of external systems.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.