API mocking and stub servers
Standalone servers that stand in for a dependency you cannot call: defining stubs, matching requests, and recording a real service to replay. Interviewers probe how the stub stays honest.
on this pageshowhide
guide
overview
~1 minAn API stub server is a separate process that answers HTTP calls in place of a dependency your code cannot reach during a test: a partner API, a payment provider, a service another team owns. WireMock, MockServer and Mountebank are the tools most questions name. Interviewers probe them because producing a fake answer is easy; knowing whether the fake still tells the truth is not. A suite that passes against a stand-in proves only that your client copes with the replies someone wrote down. The hub splits four ways. [Stand-in definitions](/topics/dev-api-mocking-tools-stubs) is about one entry: the request criteria that select it, the canned reply it returns, and which entry wins when several match. [Lifecycle and isolation](/topics/dev-api-mocking-tools-runtime) is where the server runs (inside the test process, as a standalone jar or container, shared across pipelines, or operated by a vendor) and what gets wiped between tests. [Transport conditions](/topics/dev-api-mocking-tools-wire) covers getting traffic to the stand-in, recording a real service, HTTPS, and making replies slow or broken on purpose. [Fidelity risks](/topics/dev-api-mocking-tools-fidelity) asks how you catch a stand-in that has drifted from the real thing: the request journal, near-miss reports, catch-all entries, and regenerating stubs from the live service or a specification. Junior rounds ask how a stub is written and matched and how a server is started. Senior and principal rounds turn into failure stories: a stub that stopped answering after someone else's change, a flaky suite caused by state leaking between tests, a green build over a mock that no longer resembles production, a shared instance that has outgrown the teams using it. Learn how an entry is defined and matched first, then lifecycle and reset. Transport conditions and fidelity both build on those two.
primer
### A stand-in is a claim about another system Every entry asserts that the dependency would answer this request like this. The server cannot check that claim; it serves whatever was registered. That is why interviewers keep returning to fidelity: a stub suite is worth exactly as much as its entries describe the real service honestly, and someone notices when the real service moves. ### Matching decides which fake you are testing against An arriving request is tested against predicates on method, URL or path, headers, query parameters and body. Matching is usually partial, so whatever you leave unnamed is unconstrained. A predicate can be too loose and answer calls it was never meant for, or too tight and miss without anyone noticing. When several entries match, an explicit precedence rule picks one, which means a new entry added by somebody else can take over traffic while yours stays untouched. ### The reply is only what you declared A stub hands back the status, headers and body it holds. The server derives nothing from the incoming call unless templating is switched on. Missing headers, text versus binary bodies, and replies that must change from one call to the next are where hand-written replies drift from real ones. ### State lives in the server, not in the test Registered stubs, scenario state and the request journal persist for as long as the process runs. An embedded server usually lives and dies with its test fixture; standalone and shared servers outlive many tests. Deciding what is cleared between tests, and how, is the core of isolation, and leaked state is a classic source of failures that depend on test order. ### Verification reads the journal Asserting that a call arrived, or arrived a given number of times, means reading the server's log of received requests. A disabled, capped or shared journal changes what those assertions can prove, and a negative assertion is only as good as the request description it is built from. ### Healthy and instant is the least interesting case Real dependencies time out, reset connections and send malformed data. Stub servers can delay replies and break them below the HTTP layer, which is how a client's timeout, retry and error branches get exercised before production does it for you. ### Recorded and generated stubs are snapshots Recording a live service, or generating entries from an OpenAPI document, gives stubs that start out faithful, as of the moment they were made. Keeping them current is a process of re-capturing, diffing and reviewing, not a switch on the server.
- Stub mapping
- One stand-in entry in WireMock: a request pattern that selects incoming calls, plus the response returned when it matches. Mappings can be registered in code, over HTTP, or as JSON files.
- Expectation
- MockServer's name for a stand-in entry: a request matcher paired with an action, such as returning a response, forwarding the call or producing an error.
- Imposter
- Mountebank's unit of fake service: a listener on one port and protocol holding an ordered list of stubs, each with predicates and responses.
- Predicate
- A condition an incoming request must satisfy for an entry to apply, expressed over method, URL, headers, query parameters or body.
- Stub priority
- WireMock's number for choosing among several matching stubs. Lower numbers are served first; among equal numbers, the most recently added stub wins.
- Request journal
- The server's record of the requests it received. Verification, unmatched-request lists and near-miss reports all read it; it can be capped or switched off.
- Near miss
- A diagnostic pairing a request that matched nothing with the closest registered entry, ranked by how far apart they were and naming the fields that differ.
- Admin API
- HTTP endpoints on a running stub server for registering, listing and deleting entries, resetting state, reading the journal and checking health.
- Scenario
- WireMock's state machine for stubs: the same request gets different replies depending on the state that earlier calls left behind.
- Response templating
- Rendering a reply's body or headers from the incoming request, for example echoing a path segment. In WireMock it has to be enabled before it applies.
- Record and playback
- Forwarding calls to the real service, saving its replies as stand-in entries, and answering later runs from the saved copies without the real service.
- Fault injection
- Making the stand-in fail below HTTP, by dropping or resetting the connection or sending garbage, rather than returning an error status code.
- Catch-all stub
- A low-precedence entry that answers any request. It stops unmatched calls from failing, and with them the signal that something was never stubbed.
Follow one call through a stub server. The code under test is configured with the stand-in's base URL instead of the real one, or keeps the real host and routes through the server as a forward proxy. The server logs the request in its journal and tests it against every registered entry. Matching entries are ordered by precedence and the first one answers. If none match, the server sends its not-found reply and keeps the call as unmatched, which is the raw material for near-miss reports. The chosen entry's reply goes back exactly as declared, possibly delayed or deliberately broken, or the entry forwards the call upstream and, while recording, saves what came back as a new entry. The four sections hang off that path: - **Stand-in definitions** own the matching and reply steps. - **Lifecycle and isolation** own everything around the path: when the server starts, how entries are loaded (code, files, the admin API) and what a reset clears between tests. - **Transport conditions** own how the call reaches the server and how the reply leaves it: proxying, recording, TLS, delay and faults. - **Fidelity risks** own the journal and the question every other section raises: does this entry still describe the real service? A single WireMock mapping file carries several of those decisions at once: ```json { "priority": 1, "request": { "method": "POST", "urlPath": "/orders", "bodyPatterns": [ { "equalToJson": "{\"sku\": \"A-100\"}", "ignoreExtraElements": true } ] }, "response": { "status": 201, "headers": { "Content-Type": "application/json" }, "bodyFileName": "order-created.json", "fixedDelayMilliseconds": 300 } } ``` The body matcher is loosened on purpose to tolerate extra fields; the explicit priority puts this entry ahead of default-priority ones; the media type is spelled out because the server will not add it; the body lives in a file beside the mappings; and the delay makes the client's timeout budget part of the test. Each of those choices is a point where the stand-in can quietly stop resembling the real service.
- Incoming Request Criteria →
How a request picks an entry: the criteria, partial matching and precedence that every later section assumes.
- Canned Replies →
What an entry sends back: status, headers, bodies, templating and replies that change across calls.
- Lifecycle and Isolation →
Where the server runs and what is reset between tests, the usual root of flaky stub-backed suites.
- Transport Conditions →
Proxying, recording, TLS, and the delays and faults that exercise a client's failure paths.
- Request Journal →
Verifying what actually arrived, and what a capped, shared or disabled journal can no longer prove.
- Staying Current →
Keeping recorded and generated stubs in step with the real service once they exist.
Raising a WireMock
atPrioritynumber to make a stub win: lower numbers are served first, so a bigger number pushes the stub further down the queue.Assuming a header or query-parameter criterion demands equality, when it is usually a subset check that lets every parameter you did not name through unchecked.
Leaving
Content-Typeoff a JSON stub and then debugging the client's parser instead of the stub that never declared a media type.Clearing stubs between tests but not the request journal or scenario state, then chasing failures that only appear in a particular test order.
Adding a catch-all or proxy fallback for convenience, so unstubbed or mistyped calls get a cheerful 200 or reach the real service instead of failing.
Trusting a negative assertion without checking its request description: a typo in the path makes it pass whatever the client actually sent.
Counting calls on a long-lived shared server with a capped journal, where old entries are dropped silently and verification under-reports.
Stubbing only healthy, instant replies, so timeout, retry and broken-connection branches first run in production.
WireMock, MockServer and Mountebank solve the same problem with different centres of gravity. WireMock comes from the Java world and runs embedded in a test, as a standalone jar or as a container, with JSON mapping files as a common, reviewable format. MockServer is also Java-based and leans on expectations and verification driven through a client API, plus building expectations from OpenAPI documents. Mountebank is a standalone server configured over its REST API or a config file, and speaks protocols beyond HTTP, which makes it independent of the language the tests are written in. Interviewers also expect you to place a stub server among its neighbours. In-process mocks, such as Mockito or a fake HTTP client, never touch the network: faster, but they skip serialization, HTTP semantics and connection handling, which a stub server exercises. Contract-testing tools such as Pact and Spring Cloud Contract attack the fidelity gap directly by checking a consumer's expectations against the real provider. Mock servers generated from an OpenAPI specification, Prism being one, trade hand-written detail for staying in step with the spec. Hosted mock services and a provider's own sandbox move the stand-in out of your repository: a sandbox runs the vendor's real rules, while a hosted mock serves only the replies you configured. Testcontainers is a common way to start a standalone stub server per suite.
explore
- Stand-In Definitions31 questions
- Incoming Request Criteria18 questions
- Canned Replies13 questions
- Lifecycle and Isolation32 questions
- Hosting Shapes13 questions
- Fresh State per Test13 questions
- Vendor-Operated Stand-Ins6 questions
- Transport Conditions22 questions
- Interposing on Traffic13 questions
- Faults and Delay9 questions
- Fidelity Risks25 questions
- Request Journal9 questions
- Permissive Defaults8 questions
- Staying Current8 questions
questions
110 · 4 sectionsIn WireMock, what does withRequestBody(equalToJson(...)) require of a request body?
basics
~20 sIn WireMock, withRequestBody(equalToJson(...)) parses the request body as JSON and requires it to equal your expected document exactly. Extra fields, missing fields and reordered arrays all make it miss. Two optional flags relax extra elements and array order.
In WireMock, why does a stubbed body containing `{{request.path}}` come back unrendered?
basics
~20 sWireMock renders a stub body only when the response-template transformer is attached to that response. Without it, WireMock treats the body as literal bytes and returns the Handlebars source unchanged. Attach it with withTransformers, or launch WireMock with --global-response-templating.
In WireMock, how do you make one dive-log endpoint answer PENDING first and SIGNED on the next call?
basics
~20 sPut both WireMock stubs into one scenario with inScenario. The first requires the start state and calls willSetStateTo to move the conversation on. The second requires that new state and answers only once the first has served.
In MockServer, how do you match only requests that are missing an `X-Sweep-Tenant` header?
basics
~20 sNegate the header name. MockServer holds request names and values as NottableString values, so a header built from not("X-Sweep-Tenant") matches only calls that carry no such header. Negating the value instead matches a header that is present but different.
In MockServer, does an expectation naming one query-string parameter still match a request that sends three?
basics
~20 sYes. MockServer matches on a subset, not on equality. Every header, cookie and query-string parameter you name is a constraint the request must satisfy; every one you do not name is ignored, however many the client sends.
In WireMock, what do GET, POST and DELETE on /__admin/mappings each do?
basics
~20 sWireMock's admin API at /__admin/mappings lists every registered stub on GET and registers one new stub from the posted body on POST. DELETE on the same path removes all of them. Any HTTP client can drive it while the server runs.
What is a hosted mock service, and what does a team give up by adopting it?
basics
~20 sA hosted mock service is a stub server a vendor runs for you. Its canned replies live in an account on their platform, reachable at an address they control. What you give up is custody: review, rollback and availability.
In mountebank, how does a test worker learn the port its marina-berth imposter was given?
basics
~20 sThe POST /imposters response is the created imposter, and its port field holds the number mountebank bound. Read it from that response, or list running imposters with GET /imposters, then build the worker's base URL from it.
In WireMock, which reset call empties the request journal without removing any turbine-status stub?
basics
~20 sCall resetRequests() on WireMock's WireMockServer, or resetAllRequests() from its static client DSL; over the admin API it is DELETE /__admin/requests. It resets the request journal alone, so stub mappings, scenario state and global settings all survive untouched.
In WireMock, how do you remove one run-time stub without clearing every other mapping?
basics
~20 sCall DELETE /__admin/mappings/{id} with the id WireMock returned when the stub was registered. That removes exactly that mapping and leaves the rest in place, while DELETE on the collection path clears every registered mapping at once.
In Mountebank, what do proxyOnce, proxyAlways and proxyTransparent each do to a proxied request?
basics
~20 sMountebank's proxyOnce forwards the first matching glossary request to the real service and answers later identical ones from the saved reply. proxyAlways forwards every matching request upstream. proxyTransparent forwards everything and saves nothing, staying a pure pass-through.
How do you start WireMock standalone so it records the kayak-rental API into stub mappings?
basics
~20 sRun WireMock standalone with --record-mappings and --proxy-all pointed at the kayak-rental base URL. Every request is forwarded upstream and the real reply is written back as a stub mapping. Large response bodies are extracted into separate body files.
In WireMock, what do startRecording() and stopRecording() do to kayak-rental traffic?
basics
~20 sIn WireMock, startRecording puts the running server into recording mode against a target base URL. WireMock's stopRecording ends the session and returns a SnapshotRecordResult holding the stub mappings built from the traffic. Both are also WireMock admin routes.
What does WireMock serve at GET /__admin/certs/wiremock-ca.crt, and who needs it?
basics
~20 sIt serves the public CA certificate WireMock signs browser-proxy certificates with. A client proxied through WireMock must install it in its trust store, or the call fails before any stub is matched. The private key stays on the server.
In WireMock, what do --https-port, --https-keystore and --keystore-password do?
basics
~20 sWireMock's --https-port opens an extra TLS listener on that port. --https-keystore points at a Java keystore holding the certificate WireMock presents there, and --keystore-password unlocks it. Omit both and WireMock serves its own bundled self-signed certificate instead.
In MockServer, how do you verify that a POST to /catalogue/v1/holds actually arrived?
basics
~20 sMockServer keeps a journal of every request it receives, and MockServerClient.verify asserts against it. Pass a request definition describing the POST plus a VerificationTimes count. When nothing matches, verify throws an AssertionError listing the requests the journal did record.
In WireMock, what does the --no-request-journal flag switch off, and what then happens to verify()?
basics
~20 sWireMock's --no-request-journal flag stops the server recording the requests it receives. Because nothing is recorded, verification is not weakened but abolished: the disabled journal raises RequestJournalDisabledException. A verify() call after that flag can never pass, whatever the client sent.
In WireMock, what does makeStubsPersistent(false) change about the stubs a re-recording produces?
basics
~20 sWith makeStubsPersistent set to false, WireMock keeps the regenerated stubs in memory only: they serve requests while the instance lives and vanish on restart. Its default, true, writes each one as a JSON file under the mappings directory.
In MockServer, what does each VerificationTimes factory assert about how often a request arrived?
basics
~20 sVerificationTimes carries six factories: never, once, exactly, atLeast, atMost and between. Each turns a MockServer verification from at least one matching request into a precise count assertion, so a duplicated or missing hold request fails the test rather than passing.
In MockServer, what does upsert(openAPIExpectation(...)) build from an OpenAPI document?
basics
~20 sMockServer reads the OpenAPI document, then creates one expectation for each operation it selects, matching that operation's method, path and declared parameters. Each expectation replies with the response the document declares. The entry point is upsert(OpenAPIExpectation...) on MockServerClient.