Mock vs. Stub: What's the Difference?

A stub answers. A mock checks. Here is the difference in one table, the code for each, and how to choose when the thing you are replacing is a third-party API.

The short answer

A stub stands in for a dependency and returns canned answers, so the code under test can run. The test then checks the result: what your code returned or what state it left behind.

A mock stands in for a dependency and records how it was called. The test then checks the interaction: that your code called the right method, with the right arguments, the right number of times.

Both are kinds of test double, the umbrella term from Gerard Meszaros's xUnit Test Patterns. The other three are the dummy, the spy and the fake.

The five test doubles

Most arguments about mocks and stubs are really arguments about words. Meszaros named five kinds of stand-in, and Martin Fowler's essay Mocks Aren't Stubs made the distinction widely known. Each one answers a different question:

DoubleWhat it doesWhat the test asserts
DummyFills a parameter that is never used.Nothing about it.
StubReturns canned answers to the calls the test makes.The result or state of the code under test.
SpyA stub that also records the calls it received.The result, then the recorded calls afterwards.
MockIs set up with expected calls and fails when they don't happen.The calls themselves: method, arguments, count, order.
FakeA working implementation with a shortcut, such as an in-memory database.The result, against something that behaves like the real thing.

The line that matters is the last column. Stubs, spies and fakes support state verification: run the code, then look at what came out. Mocks support behavior verification: run the code, then check what it did to its collaborators.

A stub, in code

Say checkout() charges a card through a payments client and returns an order status. To test the happy path you don't care how the charge is made, only that checkout reacts correctly to a successful one. A stub is enough:

import { expect, test } from "vitest";
import { checkout } from "./checkout";

test("a successful charge marks the order paid", async () => {
  // Stub: canned answer, no expectations.
  const payments = {
    createCharge: async () => ({ id: "ch_test_1", status: "succeeded" }),
  };

  const order = await checkout({ id: "ord_1", amount: 4200 }, payments);

  // State verification: assert on the outcome.
  expect(order.status).toBe("paid");
});

Swap the canned answer for { status: "failed" } and the same stub drives the failure path. A stub is how you put the code under test into a situation that would be slow, costly or impossible to arrange against the real service.

A mock, in code

Now say checkout must also post a message to a Slack channel when an order is paid. Posting returns nothing your code uses, so there is no result to inspect. The only way to know it happened is to check the call. That is a mock's job:

import { expect, test, vi } from "vitest";
import { checkout } from "./checkout";

test("a paid order is announced in #orders", async () => {
  const payments = {
    createCharge: async () => ({ id: "ch_test_1", status: "succeeded" }),
  };
  // Mock: records calls so the test can verify them.
  const notifier = {
    postMessage: vi.fn().mockResolvedValue({ ok: true }),
  };

  await checkout({ id: "ord_1", amount: 4200 }, payments, notifier);

  // Behavior verification: assert on the interaction.
  expect(notifier.postMessage).toHaveBeenCalledTimes(1);
  expect(notifier.postMessage).toHaveBeenCalledWith(
    expect.objectContaining({ channel: "#orders" }),
  );
});

Strictly, vi.fn() checked after the fact is a spy, and a mock in Meszaros's sense declares its expectations before the code runs (Sinon's sinon.mock(obj).expects("method") works that way). Most teams call both "mocks", and the practical point is the same: the assertion is about the call, not the outcome.

Mock vs. stub, side by side

StubMock
PurposeFeed the code under test the inputs it needsCheck the code under test sends the right outputs
VerificationState: the result or what was storedBehavior: which calls were made, and how
Can fail the test by itselfNoYes, when an expected call is missing or wrong
Typical targetQueries: reads, lookups, fetchesCommands: sends, writes, notifications
Coupling to implementationLow: only the answers are fixedHigher: the exact calls are fixed
Breaks on a harmless refactorRarelyOften, if the calls change but the outcome doesn't
Remembers earlier callsNoOnly to verify them, not to change later answers

A useful rule of thumb: stub queries, mock commands. If your code asks a dependency for something, stub the answer and assert on what your code does with it. If your code tells a dependency to do something and gets nothing useful back, verify the call.

Why the names are so confusing

Tools rarely use the words the way the taxonomy does, which is most of the reason this question gets asked:

  • Jest and Vitest call jest.fn() / vi.fn() a "mock function". It is used as a stub (mockReturnValue) and as a spy (toHaveBeenCalledWith), often in the same test.
  • Mockito creates every double with mock(). Whether it acts as a stub (when(...).thenReturn(...)) or a mock (verify(...)) depends on what the test does with it.
  • Python's unittest.mock.Mock is likewise both: set return_value to stub, call assert_called_with to verify.
  • Sinon.JS keeps the words apart, with separate sinon.stub(), sinon.spy() and sinon.mock() APIs.
  • WireMock, an HTTP-level tool, calls its response mappings stubs (stubFor(...)) and checks received requests with verify(...), so one server can play both roles.

So when a library says "mock", read the test: if it only asserts on results, the double is acting as a stub.

Stubs, mocks and fakes for third-party APIs

The same three roles show up one level down, when the dependency is an HTTP API such as Stripe, Slack or GitHub rather than an object in your code:

  • A stub server returns a fixed response for each matched request. Fast and deterministic, and the right tool for forcing an exact payload or error code. It has no memory: create a customer, then fetch it, and the fetch returns whatever was configured, not what you created.
  • A mock server does the same and also records the requests it received, so the test can assert that, say, exactly one refund was requested. It still has no memory between calls.
  • A fake, or stateful simulator, runs the API's behavior: a POST creates a record, a later GET returns it, a list includes it and invalid state changes are rejected. Hosted simulators, Rystic among them, are fakes of this kind for APIs like Stripe, Slack and GitHub.

Stubs and mocks are the right choice for unit tests and for single calls (when HTTP mocks are the right choice covers the cases). They fall short when a test spans several calls that depend on each other, such as create, then update, then list, because every answer was written by hand and none of them reflects what the earlier calls did. That is where a fake earns its place: in integration tests that follow a workflow from start to finish.

Any hand-written double can drift from the real API without anyone noticing. Whatever you use, check it against the provider's current API reference, or pair it with contract tests or a simulator that is itself verified against the live service.

Which one to use

  1. The code reads something and you test what it does with the answer: use a stub.
  2. The code sends something and the call is the only observable effect: use a mock (or a spy).
  3. The parameter is required but the test never touches it: pass a dummy.
  4. The test spans several calls where later answers depend on earlier ones: use a fake or a stateful simulator.
  5. You need to know the double still matches the real service: add contract tests or verify the double against the real API.

Two habits keep suites healthy. Mock only what you own or what has no observable result, because every verified call is a line that breaks when the implementation changes. And keep the number of verified calls per test small: one behavior per test is easier to read and to fix.

Frequently asked questions

Is a mock a type of stub?

Not quite. Both are test doubles and both can return canned answers, but a mock also carries expectations about how it is called and can fail the test on its own. A stub never fails a test; it only supplies answers.

What is the difference between a mock, a stub and a fake?

A stub returns fixed answers, a mock verifies the calls it receives, and a fake is a working, simplified implementation (an in-memory database, a stateful API simulator) that behaves like the real thing across many calls.

What is the difference between a spy and a mock?

A spy records calls and lets the test inspect them afterwards. A mock in the strict sense is told what calls to expect before the code runs and checks them itself. Most libraries blur the two.

Should I mock or stub a third-party API?

Stub it to drive your code down a specific path, such as a declined card or a 429. Verify calls when sending the request is the behavior under test. For flows that span several dependent calls, use a fake or stateful simulator so later responses reflect earlier ones.

Further reading