Test Doubles: Mocks vs Stubs vs Fakes (Prompt Decision Table)

Of 640 tests in the Pawtrack Clinic app, 210 touch the card-payment integration being prepared for a 40-clinic rollout. The suite takes 9 minutes and fails 4 percent of the time on a clean branch, almost always in a payment test that asserts on a mock and then disagrees with itself about call order. Nothing is broken in production. The tests are arguing with a double that was chosen by habit.

Mock, stub, fake, spy, and a real sandbox are not interchangeable, and the difference shows up in what the test can prove. The table below scores each double against a payment flow that has to work the same way in 40 clinics, then each option gets a prompt you can hand to ChatGPT when you want the test written rather than described. If the test is failing for a different reason, the error handling comparison covers the failure paths around the charge itself.

Choosing a Double: Comparison Table

DoubleWhat it replacesUse it whenAssertion it allowsUpkeep
StubOne call, fixed answerYou only need a return value to reach the branch under testOutput of your code, never the collaboratorLow, one function per case
MockOne call, with expectationsThe contract itself is the behaviour you must protectThat a call happened, with which arguments, in what orderHigh, breaks on refactor
FakeA whole dependency, working but simplifiedMany tests exercise the same rules through the same interfaceState after a sequence of operationsMedium, one implementation to keep honest
SpyA real object that records callsYou need real behaviour and a record of what was invokedBoth result and call historyLow to medium, leaks into shared state
SandboxNothing, the vendor’s test environmentBefore a rollout, once, as a contract checkThat the real API still matches your assumptionsLow code, high latency and flakiness

Choose by asking what a failure should tell you. If a red test should say “my branch logic is wrong”, a stub is enough. If it should say “someone changed the call sequence”, you need a mock, and you should accept that the test will break for reasons that are not bugs. If it should say “the refund rules are wrong”, only a fake will carry that weight across 210 tests.

Stubs Answer, Mocks Record, Fakes Behave

A stub is a question with a canned answer. In the Pawtrack code, the charge function needs to know whether the gateway returned an approval or a decline so the appointment can be marked paid or held. A stub returns “declined” and the test checks that the appointment stays held. The stub has no opinion about whether the gateway was called twice, and that is the point: the test fails only when the branch is wrong.

A mock is a recording device with a script. It asserts that the code called authorize with the right amount, currency, and idempotency key, and it fails when a refactor renames the method. That is a real signal when the contract is the thing you are protecting, which is true for payment calls and false for almost everything else. Pawtrack’s 4 percent flake lives here: three mocks assert call order on a retry path that legitimately runs calls in parallel.

A fake is a working stand-in with the same interface and simpler rules. The Pawtrack fake keeps a dictionary of charges, enforces one charge per idempotency key, and returns a refund object with a decreasing balance. It is about 120 lines, it lives in the test folder, and 190 tests use it without knowing. When the team added partial refunds, one file changed and 190 tests kept running.

Writing Each Double With a Prompt

Stub for a branch. The prompt names the branch and forbids assertions on the collaborator, which keeps the double from turning into a mock.

Write a unit test for the function markAppointmentPaid in Pawtrack Clinic's booking service. Language: TypeScript with Jest. The payment gateway is injected as an interface with a single method, charge, returning an object with status and transactionId. Stub charge to return status "declined" with no transaction id. Assert only that the appointment status remains "held" and that no receipt record is created. Do not assert how many times charge was called.

Mock for a contract. Use it once, at the boundary, and assert the arguments rather than the sequence unless order truly matters.

Write a Jest test that verifies Pawtrack's payment adapter calls the gateway exactly once per appointment with an idempotency key derived from the appointment id. Mock the gateway interface. Assert the call arguments: amount in minor units, currency GBP, idempotency key equal to the appointment id, and a description under 40 characters. Do not assert call order against other collaborators. Include one test where the adapter is called twice with the same appointment and the gateway still receives one request.

Fake for a rule set. The value is in the fake’s constraints, so make the model state them explicitly before it writes the tests.

Build an in-memory fake of Pawtrack's payment gateway for tests. Behaviour: charges are stored by idempotency key, a repeat key returns the original charge rather than creating a second one, refunds cannot exceed the captured amount, and a refund on a declined charge throws a domain error. Keep it under 150 lines, no network calls, no timers. Then write 8 tests against the fake covering duplicate keys, partial refunds, over-refunds, and a refund on a declined charge.

Audit pass. Before the rollout, ask which existing tests are asserting on doubles in ways that will not survive 40 clinics.

Here is a list of 210 test names from Pawtrack's payment suite. Group them by which double they most likely use (stub, mock, fake, sandbox) based on the name and the assertion in the comment. Flag any test whose name suggests it asserts call order, any test that depends on wall-clock time, and any test that would pass if the gateway returned a success for every request. Output a table with test name, suspected double, risk, and a one-line suggested rewrite.

The Maintenance Bill at 40 Clinics

A mock costs nothing to write and a lot to keep. Every rename, every extracted function, every added optional parameter breaks a test that was never about behaviour. Pawtrack measured this: 68 percent of its payment test churn over one quarter came from four mock-heavy files, and the fixes were mostly string changes in expectations.

A fake costs a day to build and then almost nothing. The cost moves to correctness: a fake that drifts from the real gateway gives you 190 green tests and a production bug. The mitigation is one sandbox contract test per release, run against the vendor’s environment, asserting the same cases the fake encodes. That test is slow and occasionally flaky, and it is the only thing keeping the fake honest.

A stub costs little either way, which is why it should be the default. Most tests do not need to know that a collaborator was called; they need a value so the code under test can proceed.

For the rollout itself, the sequence matters more than the ratio. Pawtrack runs the sandbox contract test on every release candidate, the fake for all business-rule tests, mocks only for the three adapter contracts that a vendor could break, and stubs everywhere else. The team wrote that policy down after the flake rate hit 4 percent, and the suite dropped to 6 minutes. The prompt patterns behind those tests are collected in our unit test prompt guide.

Rules for Payment Code Specifically

Three rules survive contact with a real gateway. Never assert call order across independent requests, because retries and parallel captures will make the order non-deterministic and the test will fail for a correct system. Always test the duplicate path, since an idempotency key that is not enforced is the most expensive bug in the flow. Never let a test depend on the current time, because a payment authorized at 23:59 on the last day of a month will settle in the next one and your assertion about the settlement date will be wrong once a month.

Then decide what a mock is allowed to protect. At Pawtrack the answer is the adapter boundary and nothing else. Business rules live in the fake, branch logic lives behind stubs, and the vendor contract lives in the sandbox. Any test that does not fit one of those three is usually a test that should be deleted, and deleting it is cheaper than maintaining a double nobody trusts. The review checklist in our code review prompts includes a line for exactly this question.

Sources & Notes

Pawtrack Clinic, the 640-test suite, the 210 payment tests, the 9-minute runtime, and the 40-clinic rollout are an illustrative scenario, not a real product. Code samples are described rather than executed, so adapt names and interfaces to your own codebase before pasting a generated test into a repository. Payment APIs differ in their idempotency semantics and refund windows, so verify behaviour against the vendor’s current documentation rather than against a model’s description of it.

声明:1.本站所有文章,如无特殊说明或标注,均为本站原创发布。本网站中【文本生成/文生图】使用了DeeSseek人工智能生成内容技术, 算法来源说明:本网站未自行开发、训练或部署深度合成算法,所使用的人工智能算法来自:DeepSeek、Chatgpt、Google Gemini。 2.为了网站加载速度优化,本站预览图片进行压缩处理,所以有些不是太清晰,并不影响AI提示词生图、AI设计等内容。3.任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。--GUUNN.COM