Mock Server Pattern: Isolate Tests from External APIs
Stand up a fake HTTP server that returns canned responses, so integration tests run without real dependencies. Covers WireMock, nock, MSW, Mountebank, and Python's responses.
Overview
A mock server is a standalone HTTP server that returns pre-configured responses instead of forwarding requests to real services. Your code under test talks to it over a real socket — real DNS, real TCP, real serialization — but the other end is a box you control. In integration tests, mock servers replace external dependencies — payment gateways, third-party APIs, email providers — so the suite runs fast, deterministically, and with no network access at all.
The distinction that matters: unlike in-process test doubles, which swap a function or object inside your own process, a mock server lives at the network boundary. That means it exercises the entire HTTP stack — JSON serialization, headers, status codes, timeouts, redirects — the exact places where integration bugs actually hide.
When to Use
- Integration tests that depend on external HTTP APIs you don’t control.
- Verifying how your code handles API errors, timeouts, rate limits, and malformed payloads — the cases a sandbox refuses to produce on demand.
- CI pipelines that must run without network access or API keys.
- Resilience testing: simulating slow, flaky, or partially broken services.
- Contract testing — the consumer mocks the provider (or vice versa) to verify the interface independently.
When NOT to Use
- Unit tests — an in-process mock or stub is faster and simpler (
jest.fn(),unittest.mock). Mock servers sit in the integration slice of the test pyramid, not at its base. - When you need to validate against the real API — use a sandbox environment for that final check.
- When the “server” would just be a one-line stub — spinning up HTTP machinery for a function call is overkill.
- When the mock becomes more complex than the API it replaces — that’s a signal to test against the real thing.
Solution
WireMock (Java/JVM)
The heavyweight option: a real server process, JUnit integration, rich request matching, and JSON file mappings you can also run in Docker.
// Java — WireMock standalone server
import com.github.tomakehurst.wiremock.WireMockServer;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
class PaymentGatewayMock {
static WireMockServer wireMockServer;
@BeforeAll
static void startServer() {
wireMockServer = new WireMockServer(wireMockConfig().port(8089));
wireMockServer.start();
}
@AfterAll
static void stopServer() {
wireMockServer.stop();
}
@BeforeEach
void resetMocks() {
wireMockServer.resetAll();
}
@Test
void testSuccessfulPayment() {
// Stub the payment endpoint
wireMockServer.stubFor(post(urlPathEqualTo("/api/charges"))
.withHeader("Authorization", matching("Bearer .*"))
.withRequestBody(equalToJson("""
{
"amount": 1000,
"currency": "usd",
"source": "card_token_123"
}
"""))
.willReturn(aResponse()
.withStatus(201)
.withHeader("Content-Type", "application/json")
.withBody("""
{
"id": "ch_12345",
"amount": 1000,
"currency": "usd",
"status": "succeeded"
}
""")));
// Test your code that calls the payment gateway
PaymentResult result = paymentService.charge(1000, "usd", "card_token_123");
assertEquals("succeeded", result.getStatus());
assertEquals("ch_12345", result.getChargeId());
// Verify the request was made
wireMockServer.verify(postRequestedFor(urlPathEqualTo("/api/charges"))
.withHeader("Authorization", matching("Bearer .*")));
}
@Test
void testPaymentDeclined() {
wireMockServer.stubFor(post(urlPathEqualTo("/api/charges"))
.willReturn(aResponse()
.withStatus(402)
.withHeader("Content-Type", "application/json")
.withBody("""
{
"error": {
"code": "card_declined",
"message": "Your card was declined"
}
}
""")));
PaymentException ex = assertThrows(PaymentException.class, () ->
paymentService.charge(1000, "usd", "card_token_123")
);
assertEquals("card_declined", ex.getErrorCode());
}
}
WireMock with response templating
Handlebars placeholders pull values out of the incoming request — handy for echo-style APIs:
// Java — WireMock with Handlebars templating
wireMockServer.stubFor(get(urlPathEqualTo("/api/users/{{userId}}"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("""
{
"id": "{{request.path.userId}}",
"name": "User {{request.path.userId}}",
"email": "user{{request.path.userId}}@example.com"
}
""")
.withTransformers("response-template")));
nock (Node.js)
nock doesn’t open a port — it monkey-patches Node’s HTTP layer and intercepts outgoing calls before they hit the socket. Faster than a real server, and the isDone() check doubles as a request assertion.
// JavaScript — nock for HTTP mocking
const nock = require('nock');
describe('UserService', () => {
afterEach(() => nock.cleanAll());
test('fetches user from external API', async () => {
nock('https://api.example.com')
.get('/users/1')
.reply(200, {
id: 1,
name: 'Alice',
email: 'alice@x.com',
});
const user = await userService.getUser(1);
expect(user.name).toBe('Alice');
expect(nock.isDone()).toBe(true); // All interceptors were called
});
test('handles API error', async () => {
nock('https://api.example.com')
.get('/users/999')
.reply(404, {
error: { code: 'NOT_FOUND', message: 'User not found' },
});
await expect(userService.getUser(999))
.rejects.toThrow(NotFoundError);
});
test('handles timeout', async () => {
nock('https://api.example.com')
.get('/users/1')
.delayConnection(2000) // 2 second delay
.reply(200, { id: 1, name: 'Alice' });
// Configure your client with a 1 second timeout
await expect(userService.getUser(1))
.rejects.toThrow(TimeoutError);
});
test('verifies request headers', async () => {
nock('https://api.example.com', {
reqheaders: {
authorization: 'Bearer token123',
'content-type': 'application/json',
},
})
.post('/users', { name: 'Bob', email: 'bob@x.com' })
.reply(201, { id: 2, name: 'Bob', email: 'bob@x.com' });
const user = await userService.createUser(
{ name: 'Bob', email: 'bob@x.com' },
{ token: 'token123' }
);
expect(user.id).toBe(2);
});
});
MSW (Mock Service Worker)
MSW intercepts at the request layer — a Service Worker in the browser, the same handler contract in Node. Write the handlers once and they work in unit tests, integration tests, and a dev-server demo.
// JavaScript — MSW for browser and Node.js
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
const handlers = [
http.get('https://api.example.com/users/:id', ({ params }) => {
return HttpResponse.json({
id: Number(params.id),
name: 'Alice',
email: 'alice@x.com',
});
}),
http.post('https://api.example.com/users', async ({ request }) => {
const body = await request.json();
return HttpResponse.json(
{ id: 2, ...body, role: 'member' },
{ status: 201 }
);
}),
http.get('https://api.example.com/users/999', () => {
return HttpResponse.json(
{ error: { code: 'NOT_FOUND', message: 'User not found' } },
{ status: 404 }
);
}),
];
const server = setupServer(...handlers);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
describe('UserService with MSW', () => {
test('fetches user', async () => {
const user = await userService.getUser(1);
expect(user.name).toBe('Alice');
});
test('creates user', async () => {
const user = await userService.createUser({
name: 'Bob',
email: 'bob@x.com',
});
expect(user.id).toBe(2);
expect(user.role).toBe('member');
});
test('handles 404', async () => {
await expect(userService.getUser(999))
.rejects.toThrow(NotFoundError);
});
test('with custom handler override', async () => {
server.use(
http.get('https://api.example.com/users/1', () => {
return HttpResponse.json(
{ error: { code: 'RATE_LIMITED', message: 'Too many requests' } },
{ status: 429 }
);
})
);
await expect(userService.getUser(1))
.rejects.toThrow(RateLimitError);
});
});
Mountebank (cross-language)
Mountebank exposes a REST API for creating “imposters” — mock servers on real ports — so any language can drive it. It also speaks TCP and SMTP, which most alternatives don’t.
// JavaScript — Mountebank for cross-language mock servers
// Start: mb --port 2525
// Create an imposter (mock server on port 3000)
const imposter = {
port: 3000,
protocol: 'http',
stubs: [
{
predicates: [
{ equals: { method: 'GET', path: '/users/1' } },
],
responses: [
{
is: {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id: 1,
name: 'Alice',
email: 'alice@x.com',
}),
},
},
],
},
{
predicates: [
{ equals: { method: 'POST', path: '/users' } },
],
responses: [
{
is: {
statusCode: 201,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id: 2,
name: 'Bob',
email: 'bob@x.com',
}),
},
},
],
},
],
};
// POST to Mountebank to create the imposter
await fetch('http://localhost:2525/imposters', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(imposter),
});
Python with responses library
responses patches requests at the adapter layer — no server, no port, just registered expectations:
# Python — responses library for HTTP mocking
import pytest
import responses
@responses.activate
def test_get_user():
# Mock the HTTP call
responses.add(
responses.GET,
'https://api.example.com/users/1',
json={'id': 1, 'name': 'Alice', 'email': 'alice@x.com'},
status=200,
)
user = user_service.get_user(1)
assert user['name'] == 'Alice'
assert len(responses.calls) == 1
assert responses.calls[0].request.url == 'https://api.example.com/users/1'
@responses.activate
def test_create_user():
responses.add(
responses.POST,
'https://api.example.com/users',
json={'id': 2, 'name': 'Bob', 'email': 'bob@x.com', 'role': 'member'},
status=201,
)
user = user_service.create_user(name='Bob', email='bob@x.com')
assert user['id'] == 2
assert user['role'] == 'member'
@responses.activate
def test_api_error_handling():
responses.add(
responses.GET,
'https://api.example.com/users/999',
json={'error': {'code': 'NOT_FOUND', 'message': 'User not found'}},
status=404,
)
with pytest.raises(NotFoundError):
user_service.get_user(999)
@responses.activate
def test_retry_on_500():
# First call returns 500, second returns 200
responses.add(
responses.GET,
'https://api.example.com/users/1',
status=500,
)
responses.add(
responses.GET,
'https://api.example.com/users/1',
json={'id': 1, 'name': 'Alice'},
status=200,
)
user = user_service.get_user_with_retry(1)
assert user['name'] == 'Alice'
assert len(responses.calls) == 2
Docker-based mock server
When the test client lives in another language or another repo entirely, run WireMock as a container and version the stubs as files:
# docker-compose.yml — WireMock in Docker
services:
wiremock:
image: wiremock/wiremock:3.5.2
ports:
- "8089:8080"
volumes:
- ./test/mappings:/home/wiremock/mappings
- ./test/responses:/home/wiremock/__files
// test/mappings/users.json — WireMock mapping
{
"mappings": [
{
"request": {
"method": "GET",
"urlPath": "/api/users/1"
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"jsonBody": {
"id": 1,
"name": "Alice",
"email": "alice@x.com"
}
}
},
{
"request": {
"method": "POST",
"urlPath": "/api/users"
},
"response": {
"status": 201,
"headers": {
"Content-Type": "application/json"
},
"jsonBody": {
"id": 2,
"name": "Bob",
"email": "bob@x.com"
}
}
}
]
}
How It Works
Every tool above implements the same cycle — what differs is where the interception happens:
- Configure: the test registers stubs — a request predicate (method, path, headers, body matcher) mapped to a canned response. This is arrange-phase work.
- Intercept: the code under test fires a real HTTP call. Standalone servers (WireMock, Mountebank) answer on a real port; in-process tools (nock,
responses, MSW in Node) patch the HTTP client so the call never leaves the process. - Match and respond: the mock finds the first stub whose predicates match and returns its response. No match → connection refused, 404, or a passthrough, depending on the tool — that default is itself testable behavior.
- Verify: after the assertion, the test asks the mock whether the request actually arrived (
verify(),isDone(),responses.calls). Stubbing without verifying only tests the happy path.
Choosing a Tool
| Tool | Runs as | Best for | Watch out for |
|---|---|---|---|
| WireMock | Standalone JVM server (or Docker) | JVM stacks, record/replay, scenario state, fault injection | Heaviest setup; mappings drift into config sprawl |
| nock | In-process interceptor (Node) | Fast Node integration tests | No real socket — doesn’t test TLS/proxy weirdness |
| MSW | Request interceptor (browser + Node) | Same handlers across unit tests, integration, and demos | Service Worker setup cost in browsers |
| Mountebank | Standalone multi-protocol server | Cross-language teams; TCP/SMTP mocking | API-driven config is verbose |
| responses | In-process patch (Python) | pytest suites on requests | Only works with the requests library |
Rule of thumb: pick the lightest tool that still exercises the layer you’re testing. If a bug could live in your HTTP client config — wrong header, broken retry, bad timeout — you want a real socket (WireMock/Mountebank) or an interceptor that sees real requests (MSW/nock), not a function mock.
Mock servers in CI
The failure that shows up most in pipelines is port collision and leaked state. Run standalone servers (WireMock, Mountebank) on random or per-worker ports, and give the container a health check so the first test doesn’t race the startup. In-process tools dodge all of this — nock and responses live and die with the test process — which is part of why they’re the usual pick for CI. Whatever you choose, reset stubs between tests: a parallel suite leaking state across files produces failures that vanish the moment you run the file alone.
Variants
Proxy mode (record and replay)
WireMock can forward to the real API and record what comes back — the fastest way to bootstrap stubs for an API you don’t know well:
// Java — WireMock as a proxy: record real responses, replay in tests
wireMockServer.stubFor(any(urlMatching(".*"))
.willReturn(aResponse()
.proxiedFrom("https://api.example.com")));
// First run: records real responses
// Subsequent runs: replays recorded responses (no network needed)
Stateful mocking
Real APIs remember things. A stateful mock keeps a tiny in-memory store so POST then GET behaves like the real resource:
// JavaScript — stateful mock with MSW
let users = [];
let nextId = 1;
const statefulHandlers = [
http.get('https://api.example.com/users', () => {
return HttpResponse.json(users);
}),
http.post('https://api.example.com/users', async ({ request }) => {
const body = await request.json();
const user = { id: nextId++, ...body };
users.push(user);
return HttpResponse.json(user, { status: 201 });
}),
http.delete('https://api.example.com/users/:id', ({ params }) => {
users = users.filter(u => u.id !== Number(params.id));
return new HttpResponse(null, { status: 204 });
}),
];
Conditional responses with WireMock
Named scenarios model multi-step workflows — an order that must be created before it can be shipped:
// Java — WireMock scenarios for stateful workflows
wireMockServer.stubFor(post(urlPathEqualTo("/api/orders"))
.inScenario("Order lifecycle")
.whenScenarioStateIs("Started")
.willReturn(aResponse()
.withStatus(201)
.withBody("{\"id\": 1, \"status\": \"pending\"}"))
.willSetStateTo("Order created"));
wireMockServer.stubFor(post(urlPathEqualTo("/api/orders/1/ship"))
.inScenario("Order lifecycle")
.whenScenarioStateIs("Order created")
.willReturn(aResponse()
.withStatus(200)
.withBody("{\"id\": 1, \"status\": \"shipped\"}"))
.willSetStateTo("Order shipped"));
Best Practices
- Clean up between tests —
nock.cleanAll(),wireMockServer.resetAll(),server.resetHandlers(). Leftover stubs are the number one cause of ghost failures. - Verify requests were made —
nock.isDone(),wireMockServer.verify(),responses.calls. A stub nobody calls proves nothing. - Match on path, not full URL — exact URL matching breaks on query-param ordering and encoding differences.
- Mock at the service boundary — stub the external API, never your own internal services. Mocking yourself tests nothing.
- Use realistic response bodies — copy fields from real API docs or recorded traffic; a hand-trimmed payload hides missing-field bugs.
- Test the failure modes — 4xx, 5xx, timeouts, truncated JSON, empty bodies. The happy path is the least interesting case.
- Keep mappings organized — one file per external service for WireMock mappings, one handlers module per API for MSW.
- Use proxy mode for exploration — record real responses once, then edit them into deterministic stubs.
Common Mistakes
- Not cleaning up: leftover stubs from one test contaminate the next. Always reset.
- Mocking too broadly:
nock('https://api.example.com').get(/.*/).reply(200)swallows every call and hides bugs. - Only testing 200s: real APIs rate-limit, time out, and return malformed JSON. Mock those.
- Over-coupling to request format: matching exact JSON bodies makes tests brittle; prefer partial matching on the fields that matter.
- Forgetting verification: a stub without a
verify/isDonecheck can’t tell you the request was even attempted. - Letting mocks drift from the real API: the provider ships a breaking change, your stubs still return the old shape, tests stay green while production breaks. Refresh recordings periodically, or pair mock servers with contract tests so drift fails loudly.
See Also
- Test Double Pattern — the in-process alternative for unit tests.
- Contract Testing Pattern — what keeps mocks honest over time.
- API Mocking recipe — the quick task-oriented version.
- WireMock docs
- MSW docs
- Mountebank
- Companion examples on GitHub — runnable Python
responsessuite plus a Node nock example.
Frequently Asked Questions
What is a mock server?
A standalone HTTP server that returns pre-configured responses instead of forwarding to real services. It operates at the network level, so tests exercise the full HTTP stack — serialization, headers, status codes — not just your function calls.
How is a mock server different from a mock object?
A mock object replaces a function call inside your process; a mock server replaces an HTTP endpoint at the network boundary. Mock servers cover everything a mock object skips: JSON parsing, headers, timeouts, TLS, retries. Use mock objects for unit tests, mock servers for integration slices.
Which mock server should I use?
Match your stack: JVM → WireMock; Node.js → nock or MSW (MSW if you also need browser coverage); Python → responses or httpx-mock; cross-language → Mountebank or WireMock in Docker.
Should I use a mock server or a sandbox environment?
Both, for different jobs. Mock servers in CI: fast, offline, and able to produce errors on demand. A sandbox for one final pass before release, because only the real API confirms your assumptions still hold.
What is proxy mode?
The mock forwards requests to the real API and records the responses. Later runs replay the recordings offline — a fast way to build stubs for an unfamiliar API. Treat recordings as snapshots: they go stale the day the provider changes.
How do mock servers stay in sync with the real API?
They don't, automatically. Re-record periodically, generate stubs from the provider's OpenAPI spec where one exists, or add contract tests that fail when the real API's shape changes. A mock that never gets updated is a green checkmark lying to you.
Related Resources
Test Double: Replace Dependencies with Stubs, Spies, Fakes
How to use test doubles to isolate units under test. Covers stubs, spies, fakes, mocks, and dummy objects with examples in Python, JavaScript, and Java.
PatternContract Testing: Verify Consumer-Producer API Contracts
How to use contract testing to verify that API producers and consumers agree on request and response shapes. Covers Pact consumer-driven contracts and provider verification.
PatternTest Pyramid: Balance Unit, Integration and E2E Tests
How to structure a test suite using the test pyramid. Covers unit, integration, and E2E test proportions, the testing trophy, and the ice cream cone anti-pattern.
RecipeAPI Mocking for Testing
Build reliable tests by mocking external APIs with WireMock, MockServer, and MSW to eliminate flakiness and test edge cases.
GuideSoftware Testing Strategy Guide
A practical guide to building a layered testing strategy with unit, integration, contract, and end-to-end tests that your team will actually maintain.