What Is a Stub? (API Mocking Explained)
Stub — A stub is a canned HTTP response a mock server returns in place of the real service, so tests run against a deterministic, offline double instead of a flaky dependency.
Definition
In API mocking, a stub is the smallest building block: you tell the server "when someone calls GET /users, reply with this JSON." The server never touches the real backend — it returns your canned answer every time, which is what makes a test repeatable.
Stubs are not fakes or full mocks. They answer a fixed pattern; they do not simulate behavior. That is exactly their strength: a test that needs a known response should ask for a known response, not roll the dice on a live service that might be down, slow, or changed.
How it works
A stub is the smallest unit of API mocking: you declare a request pattern and the canned response the server should return for it. The mock server matches the incoming request against your stub and replies with your predefined body, status, and headers — never contacting the real backend.
Because the answer is fixed, a stub makes a test repeatable. The same request always yields the same response, which is exactly what you want when a test needs a known 401, a known empty list, or a known slow path.
A minimal example
In WireMock you express a stub as a mapping: a `GET /users` that returns 200 with a JSON array. You POST it to `/__admin/mappings` and every subsequent `GET /users` is answered from that definition. In Mockoon the same stub is a route you click into the GUI with a sample body.
The shape is identical across tools: a matcher (method plus path, sometimes headers or body) and a response (status, body, headers). Learn that pair once and every mock server’s stub model clicks into place.
When you need it
Use a stub whenever a test needs a deterministic answer from a dependency that is flaky, slow, paid, or not built yet. A test that requires a 401 should get a 401 every run, not whatever the real auth service feels like returning today.
Stubs also shine in demos and local development, where you want the frontend to call something believable before the backend exists. They are the fastest way to unblock work that depends on an API.
When you don’t
Don’t reach for a stub when you actually need to verify interaction — that’s a mock’s job, which records and asserts on the calls it received. A stub only answers; it can’t tell you the client sent the right request.
Don’t stub a service you control and can run locally in a test container; the real instance gives you truth a stub can’t, and adds a second source of truth for no gain. Stub the dependency you can’t reliably run, not the one you can.