Notes
The problem
Picture an order service that calls a payment provider to charge a card. Using the real provider in tests is slow and often rate limited, can cost money, is sometimes down, and may not even be built yet if another team owns it. Worst of all, you cannot make it fail on purpose: no decline, no timeout, no server error. This is a generic example; ShopRung itself does not call a payment provider.
- slow or rate limited
- costs money per call
- down when you need it
- not built yet (other team)
- shared data, unpredictable
- cannot force: a decline, a timeout, a 500, bad JSON
- a generic example: ShopRung itself has no payment API
Service virtualisation
WireMock is a real HTTP server that you control. It can run inside your test or as a standalone server in Docker. You register stubs: if a request looks like this, answer with that. You point the service under test at WireMock's address through configuration instead of the real provider's. WireMock also records every request it receives, so your test can check exactly what the service sent. This idea is called service virtualisation.
- runs a real HTTP server (in your test, or Docker)
- you register stubs: "if request looks like X, answer with Y"
- point the app at its URL via configuration
- it records every request, so tests can verify calls
A JSON stub
A stub can be a plain JSON file. The request part says: method post, path slash payments. The response part says: status two hundred and one, with a JSON body holding a payment id and status OK. Put files like this in a mappings folder, start WireMock, for example with its Docker image, and it answers immediately. Teams often share these files so every developer and tester gets the same fake provider.
{
"request": {
"method": "POST",
"urlPath": "/payments"
},
"response": {
"status": 201,
"jsonBody": {"paymentId": "pay_123",
"status": "OK"}
}
} In Java
In Java, the WireMock test annotation starts a server for the test class. Stub for post to payments will return OK with a JSON body. Then call your own code, here paying order seven, which is configured to use port eight oh eight nine. Finally, verify: WireMock received a post to payments, and the amount cents in its JSON body was four nine nine nine. The verify step is as important as the stub, because it proves your service sent the right thing.
@WireMockTest(httpPort = 8089)
class ChargeTest {
@Test void chargesTheTotal() {
stubFor(post("/payments")
.willReturn(okJson(
"{\"paymentId\":\"pay_123\"}")));
orders.pay(7); // calls 8089
verify(postRequestedFor(
urlEqualTo("/payments"))
.withRequestBody(matchingJsonPath(
"$.amountCents", equalTo("4999")))); Failures on demand
Now the real power: failures on demand. Return four oh two with a declined error, and check that your service tells the customer and does not mark the order paid. Return a five hundred. Add a fixed three second delay, and check that your timeout works. Or simulate a broken connection with a fault. These are the paths that cause real incidents, and with a real provider they are almost impossible to test.
// a decline
.willReturn(aResponse().withStatus(402)
.withBody("{\"error\":\"declined\"}"))
// a server error
.willReturn(serverError())
// slow: 3 seconds
.willReturn(ok().withFixedDelay(3000))
// broken connection
.willReturn(aResponse().withFault(
Fault.CONNECTION_RESET_BY_PEER)) Matching and state
WireMock matches on much more than the path: query parameters, headers like authorization, and values inside the JSON body. Priorities let a specific stub win over a catch all. Scenarios add state, so the first status call returns pending and the second returns paid, which is perfect for testing polling. Record mode proxies the real API once and saves real responses as stubs. And templating can echo values from the request into the response.
- match on: method, URL, query, headers, JSON body paths
- priorities: a specific stub beats a catch-all scenarios: a stateful flow 1st call PENDING, 2nd call PAID
- record mode: proxy the real API once, save the stubs
- templating: echo request data
In Python
In Python, libraries like respx for httpx, or responses for requests, intercept calls inside the test process instead of running a server. Here, a post to payments returns four oh two, and the test expects our charge function to raise a payment error saying declined. We ran three such tests, success, decline and a timeout, and all passed in seven hundredths of a second. WireMock can also serve Python tests over HTTP when you need a real server.
@respx.mock
def test_declined():
respx.post(f"{BASE}/payments")
.respond(402,
json={"error": "card_declined"})
with pytest.raises(PaymentError,
match="declined"):
charge(BASE, 7, 4999)
# success, decline, timeout:
# 3 passed in 0.07s The risk
Mocks carry one big risk. The real API changes, renames a field or adds a required header, but your stub does not. Every test stays green while production breaks. Keep mocks honest: record stubs from real traffic, use contract tests, which is the next episode, run a few tests against the provider's real sandbox, and review stubs whenever the provider announces a change.
- the real API changes, your stub does not → all tests green, prod broken
- fixes: record stubs from real calls contract tests (next episode) a few tests vs a real sandbox review stubs when APIs change
Common mistakes
Mocking mistakes. Stubbing only the happy path, which wastes the main benefit. Never verifying what was sent. Provider URLs hard coded in the app, so it cannot be pointed at a mock. Stubs that are never updated. Mocking the very service you are testing, so the test checks nothing real. And catch all stubs that answer everything with two hundred and hide wrong requests.
- only stubbing the happy path
- never verifying the request
- hard-coded provider URLs, so the app cannot be pointed at the mock
- stubs that never get updated
- mocking your OWN service in its own tests
- catch-all stubs hiding bugs
Say it like this
In the interview: I point the service at a WireMock server through configuration. I stub the success path and every failure: declines, server errors, slow responses and connection resets, and I verify the exact request my service sent. I keep stubs honest with recordings and contract tests, and run a few checks against the provider's sandbox before releases.
- "I point the service at a WireMock server via config, stub success and every failure: declines, 500s, delays and resets, and verify the exact
- request sent. I keep stubs
- honest with recordings and contract tests, plus a few
- checks against the provider
- sandbox."