QA AND TEST AUTOMATION · PART 4 · API TESTING · TECHNIQUE · 44 OF 112

WireMock Tutorial: Mocking APIs for Testing

Testing code that depends on other APIs you do not control: what service virtualisation is, WireMock stubs in JSON and in Java, request matching, verifying what was sent, simulating declines, delays and connection faults, stateful scenarios, the Python equivalent with respx (run for real: 3 passed), and the risk of mocks drifting from reality.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Fake HTTP server
  • JSON or Java stubs
  • verify requests
  • declines, delays, faults
  • scenarios
  • keep mocks honest

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.

Why not call the real one?
  • 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.

How WireMock works
  • 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.

mappings/charge-ok.json
{
  "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
@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.

Make it fail
// 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.

More features
  • 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.

pytest + respx
@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.

Keeping mocks honest
  • 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.

Avoid these
  • 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.

In the interview
  • "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."

Interview questions

Q1What is WireMock?

An HTTP mock server (service virtualisation tool) that returns stubbed responses for matching requests and records requests for verification; runs embedded in tests or standalone/Docker.

Q2Why mock third-party APIs in tests?

Speed, cost, availability, deterministic data, and the ability to simulate failures like declines, timeouts and server errors that the real API cannot produce on demand.

Q3What is the difference between a stub and verification in WireMock?

A stub defines the response for a matching request; verify checks that the service actually sent the expected request (method, URL, headers, body).

Q4How do you simulate a timeout or network failure with WireMock?

withFixedDelay (or random delays) for slow responses, and withFault (for example CONNECTION_RESET_BY_PEER, EMPTY_RESPONSE) for broken connections.

Q5What are WireMock scenarios?

State machines for stubs, so the same request can return different responses over time, such as PENDING then PAID.

Q6How do you mock HTTP calls in Python tests?

With libraries such as responses (for requests) or respx (for httpx), or by running WireMock and pointing the code at it.

Q7What is the main risk of mocking APIs?

Drift: the real API changes but stubs do not, so tests pass while production fails. Mitigate with recordings, contract tests and sandbox checks.

Q8What must the application support to be tested with WireMock?

A configurable base URL for the dependency, so tests can point it at the mock server.