Unravel › Java concepts › Testing
Faking remote services (WireMock, MockWebServer, Pact)
To test code that calls another service, you stand up a fake HTTP server that returns the answers you script: successes, errors, slow responses and broken connections.
Learn these first
At a glance
A film set built for the scene.
- 1WireMock runs a real HTTP server in the test: stubFor(get("/stock/A-100").willReturn(okJson("{\"qty\":5}"))), then your client points at wm.baseUrl()Afterwards verify(1, getRequestedFor(urlEqualTo(...))) checks what was called.
- 2OkHttp MockWebServer is lighter: server.enqueue(new MockResponse().setBody(...).setResponseCode(503)), then server.takeRequest() returns what your client sent
- 3MockRestServiceServer replaces the transport of a RestTemplate without a socketWebClient tests typically use WireMock or MockWebServer.
- 4Pact: the consumer test records its expectations as a contract file; the provider verifies it against the real implementation, so both sides can change safely
- Script failures, not only success: 500, 429, slow responses (withFixedDelay) and connection resets (Fault.CONNECTION_RESET_BY_PEER)
- A hand-written fake can drift from the real service
- WireMock starts an embedded Jetty server, matches each incoming request against the registered stub mappings by priority and specificity, and renders the response (with optional delay or fault injection)
@WireMockTestclass StockClientTest { @Test void retriesAfterServiceUnavailable(WireMockRuntimeInfo wm) { stubFor(get("/stock/A-100").inScenario("flaky").whenScenarioStateIs(STARTED) .willReturn(aResponse().withStatus(503)).willSetStateTo("recovered")); stubFor(get("/stock/A-100").inScenario("flaky").whenScenarioStateIs("recovered") .willReturn(okJson("{\"qty\":5}"))); StockClient client = new StockClient(wm.getHttpBaseUrl()); assertEquals(5, client.quantity("A-100")); }}- line 1 uses WireMockTest, the core of Faking remote services (WireMock, MockWebServer, Pact)
- line 4 uses WireMock, the core of Faking remote services (WireMock, MockWebServer, Pact)
- line 5 uses stubFor, the core of Faking remote services (WireMock, MockWebServer, Pact)
- line 6 uses willReturn, the core of Faking remote services (WireMock, MockWebServer, Pact)
- line 7 uses stubFor, the core of Faking remote services (WireMock, MockWebServer, Pact)
- line 8 uses willReturn, the core of Faking remote services (WireMock, MockWebServer, Pact)
Read the full explanation (about 1 min)
To test code that calls another service, you stand up a fake HTTP server that returns the answers you script: successes, errors, slow responses and broken connections. Contract tests (Pact) additionally prove the fake matches what the real service does.
A mental model
A film set built for the scene. The shopfront looks real from the camera, you decide exactly what the actor behind the counter says, and you can stage a fire without burning down a real shop.
How it works
WireMock runs a real HTTP server in the test: stubFor(get("/stock/A-100").willReturn(okJson("{\"qty\":5}"))), then your client points at wm.baseUrl(). Afterwards verify(1, getRequestedFor(urlEqualTo(...))) checks what was called.
OkHttp MockWebServer is lighter: server.enqueue(new MockResponse().setBody(...).setResponseCode(503)), then server.takeRequest() returns what your client sent.
MockRestServiceServer replaces the transport of a RestTemplate without a socket. WebClient tests typically use WireMock or MockWebServer.
Pact: the consumer test records its expectations as a contract file; the provider verifies it against the real implementation, so both sides can change safely.
Going deeper
Script failures, not only success: 500, 429, slow responses (withFixedDelay) and connection resets (Fault.CONNECTION_RESET_BY_PEER). Timeouts, retries and circuit breakers are untested until you do.
A hand-written fake can drift from the real service. Record real interactions, share an OpenAPI spec, or run contract tests so a changed field is noticed in the build, not in production.
Do not mock your own HTTP client class in such tests; the point is to exercise the real serialization, headers and error handling.
Under the hood
WireMock starts an embedded Jetty server, matches each incoming request against the registered stub mappings by priority and specificity, and renders the response (with optional delay or fault injection). Every request is kept in a journal so it can be verified afterwards.
Common mistakes
- Only testing success responses.
- A fake that has drifted from the real API.
- Hard-coded ports.
- Stubs shared and left over between tests.
How Unravel recognises it
When you paste code, Unravel looks for these signs of faking remote services (wiremock, mockwebserver, pact). Spotting them yourself is a good habit when you read unfamiliar code:
- Annotations:
@WireMockTest@Pact@PactTestFor@AutoConfigureStubRunner@AutoConfigureWireMock - Types:
WireMockServerWireMockWireMockRuntimeInfoMockWebServerMockResponseRecordedRequestMockRestServiceServerWireMockExtensionMockServerClientPactDslWithProviderRequestResponsePactMockRestRequestMatchersMockRestResponseCreators - Method calls:
stubFor()aResponse()urlEqualTo()urlPathEqualTo()willReturn()withRequestBody()enqueue()takeRequest()
Part of a learning path
- Testing enterprise code · previous: Testcontainers (real databases and brokers in tests) · next: Testing Kafka code
Related concepts
Frequently asked questions
What is Faking remote services (WireMock, MockWebServer, Pact)?
To test code that calls another service, you stand up a fake HTTP server that returns the answers you script: successes, errors, slow responses and broken connections. Contract tests (Pact) additionally prove the fake matches what the real service does.
What are the most common mistakes with Faking remote services (WireMock, MockWebServer, Pact)?
Only testing success responses. A fake that has drifted from the real API. Hard-coded ports. Stubs shared and left over between tests.
How can I see Faking remote services (WireMock, MockWebServer, Pact) in real code?
Paste your own Java into Unravel and it will point out where faking remote services (wiremock, mockwebserver, pact) appears, explain how it works at the detail level you choose, and draw the flow of the code around it.