ποΈ Deterministic HTTP Mocking for Standalone Daemons & Embedded Java Pipelines
Building resilient API integration test suites requires predictable, high-speed HTTP services that can run either as shared microservice simulators or as embedded, zero-collision fixtures inside CI pipelines. WireMock addresses both requirements through two deployment paradigms: WireMock Standalone and WireMock JUnit 5 Extension. Operating as a standalone process (via CLI binary or Docker container), WireMock acts as an independent network daemon reading declarative JSON stubs from file systems or remote admin APIs. When embedded inside Java test runners using @RegisterExtension and WireMockExtension, it provides lifecycle-managed, ephemeral mock servers with dynamic TCP port allocation, request verification assertions, and Handlebars response templatingβensuring deterministic API test execution without cross-thread port collisions.
WIREMOCK DEPLOYMENT PARADIGM MATRIX:
βββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββ
β DIMENSION β STANDALONE WIEMOCK (DAEMON/DOCKER) β EMBEDDED JUNIT 5 (WireMockExtension) β
βββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββ€
β Process Boundary β Out-of-process JVM or Docker cont. β Runs inside same JVM as test suite β
β Port Allocation β Typically static port (8080/8089) β dynamicPort() eliminates collisions β
β Stub Configuration β mappings/*.json & __files/* files β Programmatic Java DSL (stubFor) β
β Target Consumers β Multi-language services (Py, JS) β Java RestAssured / HttpClient tests β
β Lifecycle Control β External orchestration (CI/Compose)β Automatic per-test or per-class β
β Reset Mechanism β POST /__admin/mappings/reset β wiremock.resetAll() per test method β
βββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββ
STANDALONE DIRECTORY ROOT STRUCTURE:
wiremock-root/
βββ mappings/ # JSON stub mapping descriptors
β βββ get_student_200.json # Maps GET /v1/students/{id}
β βββ post_enrollment_201.json # Maps POST /v1/enrollments
βββ __files/ # Large/binary response bodies
β βββ large_payload.json # Body file referenced by "bodyFileName"
β βββ syllabus_guide.pdf # Binary payload served over HTTP
βββ wiremock-standalone.jar # Executable standalone JAR binary
wiremock-standalone.jar, configuring custom ports, root directories, asynchronous request delays, and verbose wire logging.
# 1. Download WireMock Standalone JAR binary
curl -sLO https://repo1.maven.org/maven2/org/wiremock/wiremock-standalone/3.4.2/wiremock-standalone-3.4.2.jar
# 2. Launch WireMock on specific HTTP & HTTPS ports with custom root folder:
java -jar wiremock-standalone-3.4.2.jar \
--port 8089 \
--https-port 8443 \
--root-dir ./wiremock-root \
--verbose \
--global-response-templating
# 3. Launch with Asynchronous Background Request Logging:
java -jar wiremock-standalone-3.4.2.jar \
--port 8089 \
--async-response-enabled=true \
--async-response-threads=10 \
--record-mappings \
--proxy-all="https://api.nikita-infotech.com"
# 4. Equivalent Docker Standalone Container Launch:
docker run -d --name wiremock-srv \
-p 8089:8080 \
-v $(pwd)/wiremock-root:/home/wiremock \
wiremock/wiremock:3.4.2 \
--global-response-templating \
--verbose
mappings/ and utilizing externalized response bodies inside __files/ with precise request matching rules (URL regex, headers, query params).
// 1. STUB DESCRIPTOR FILE: mappings/student_details_stub.json
{
"id": "9f8a10c9-bf12-4e89-a0bc-1123481029ba",
"name": "Fetch_Student_By_Id_Success",
"request": {
"method": "GET",
"urlPattern": "/api/v1/students/([A-Z]{3}-[0-9]{5})",
"headers": {
"Accept": {
"contains": "application/json"
},
"Authorization": {
"matches": "^Bearer eyJ[a-zA-Z0-9._-]+$"
}
},
"queryParameters": {
"includeCourses": {
"equalTo": "true"
}
}
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "private, max-age=300"
},
"bodyFileName": "student_response.json"
}
}
// 2. EXTERNALIZED RESPONSE BODY FILE: __files/student_response.json
{
"studentId": "STU-88219",
"fullName": "Nikita Sharma",
"email": "nikita.sharma@nikita-infotech.com",
"department": "Software Engineering",
"status": "ACTIVE",
"courses": [
{ "code": "API-PRO-101", "credits": 4 },
{ "code": "PY-AUTO-202", "credits": 3 }
]
}
@RegisterExtension. Demonstrates dynamic port binding via wireMockConfig().dynamicPort(), preventing TCP port collisions during parallel Maven Surefire runs.
package com.nikitainfotech.api.wiremock;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.hamcrest.Matchers.equalTo;
public class WireMockJUnit5DynamicPortTest {
// WireMockExtension manages server start, dynamic port allocation, and teardown
@RegisterExtension
static WireMockExtension wm = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
.build();
@AfterEach
public void resetStubs() {
// Reset all stubs and recorded request history between test executions
wm.resetAll();
}
@Test
public void testDynamicPortStubbing() {
// 1. Arrange: Stub endpoint using WireMock Java DSL
wm.stubFor(get(urlEqualTo("/api/v1/health"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"status\":\"UP\",\"cluster\":\"IN-WEST-1\"}")));
// 2. Act: Read dynamically assigned port using wm.getPort() or wm.baseUrl()
System.out.println("[+] Ephemeral WireMock instance running at: " + wm.baseUrl());
RestAssured.given()
.baseUri(wm.baseUrl())
.accept(ContentType.JSON)
.when()
.get("/api/v1/health")
.then()
.statusCode(200)
.body("status", equalTo("UP"))
.body("cluster", equalTo("IN-WEST-1"));
// 3. Assert: Verify call reached the mock server
wm.verify(1, getRequestedFor(urlEqualTo("/api/v1/health")));
}
}
package com.nikitainfotech.api.wiremock;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.hamcrest.Matchers.equalTo;
@WireMockTest(httpPort = 8089)
public class AdvancedRequestMatchingTest {
@Test
public void testMultiCriteriaRequestMatching() {
// Arrange: Configure multi-criteria matching rules
stubFor(post(urlPathMatching("/api/v1/courses/[0-9]+/enroll"))
// 1. Query parameter matching
.withQueryParam("notifyStudent", equalTo("true"))
// 2. Header matching with regex
.withHeader("X-Correlation-ID", matching("^REQ-[a-f0-9]{8}$"))
// 3. Verify absence of deprecated header
.withHeader("X-Deprecated-Auth", absent())
// 4. JSON body matching with JSONPath evaluation
.withRequestBody(matchingJsonPath("$.student[?(@.age >= 18)]"))
.withRequestBody(matchingJsonPath("$.payment.mode", equalTo("UPI")))
.willReturn(aResponse()
.withStatus(201)
.withHeader("Content-Type", "application/json")
.withBody("{\"enrollmentId\":\"ENR-99214\",\"status\":\"CONFIRMED\"}")));
// Act: RestAssured sends compliant request
RestAssured.given()
.baseUri("http://localhost:8089")
.contentType(ContentType.JSON)
.queryParam("notifyStudent", "true")
.header("X-Correlation-ID", "REQ-a1b2c3d4")
.body("{"
+ "\"student\":{\"id\":\"STU-101\",\"age\":22},"
+ "\"payment\":{\"mode\":\"UPI\",\"amount\":4999.0}"
+ "}")
.when()
.post("/api/v1/courses/101/enroll")
.then()
.statusCode(201)
.body("enrollmentId", equalTo("ENR-99214"));
// Negative Validation: Ensure non-matching request returns 404
RestAssured.given()
.baseUri("http://localhost:8089")
.contentType(ContentType.JSON)
.queryParam("notifyStudent", "true")
.header("X-Correlation-ID", "INVALID-FORMAT")
.body("{\"student\":{\"age\":17}}")
.when()
.post("/api/v1/courses/101/enroll")
.then()
.statusCode(404);
}
}
package com.nikitainfotech.api.wiremock;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import io.restassured.RestAssured;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.hamcrest.Matchers.equalTo;
@WireMockTest(httpPort = 8089)
public class WireMockProxyOverrideTest {
private static final String REAL_BACKEND_URL = "https://jsonplaceholder.typicode.com";
@BeforeEach
public void setupProxyRouting() {
// Priority 10 (Low Priority Default): Proxy all un-stubbed traffic to live backend
stubFor(any(anyUrl())
.atPriority(10)
.willReturn(aResponse()
.proxiedFrom(REAL_BACKEND_URL)));
// Priority 1 (High Priority Override): Intercept /posts/1 and return mock stub
stubFor(get(urlEqualTo("/posts/1"))
.atPriority(1)
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"id\":1,\"title\":\"VIRTUALIZED OVERRIDE TITLE\",\"userId\":99}")));
}
@Test
public void testSelectiveProxyInterception() {
// 1. Call overridden endpoint (/posts/1) -> Handled locally by WireMock stub
RestAssured.given().baseUri("http://localhost:8089")
.when()
.get("/posts/1")
.then()
.statusCode(200)
.body("title", equalTo("VIRTUALIZED OVERRIDE TITLE"))
.body("userId", equalTo(99));
// 2. Call non-overridden endpoint (/posts/2) -> Proxied transparently to live backend!
RestAssured.given().baseUri("http://localhost:8089")
.when()
.get("/posts/2")
.then()
.statusCode(200)
.body("id", equalTo(2))
.body("title", equalTo("qui est esse")); // Real live payload from jsonplaceholder!
}
}
package com.nikitainfotech.api.wiremock;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import java.util.List;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@WireMockTest(httpPort = 8089)
public class WireMockVerificationTest {
@Test
public void testWireMockInteractionVerification() {
stubFor(post("/api/v1/audit/log").willReturn(aResponse().withStatus(202)));
// Simulate application dispatching 2 distinct audit log requests
RestAssured.given().baseUri("http://localhost:8089")
.header("X-App-Id", "PORTAL_01")
.body("{\"event\":\"LOGIN_SUCCESS\",\"user\":\"Nikita\"}")
.post("/api/v1/audit/log");
RestAssured.given().baseUri("http://localhost:8089")
.header("X-App-Id", "PORTAL_01")
.body("{\"event\":\"COURSE_VIEW\",\"course\":\"API-PRO-101\"}")
.post("/api/v1/audit/log");
// 1. Assert EXACT invocation count:
verify(exactly(2), postRequestedFor(urlEqualTo("/api/v1/audit/log"))
.withHeader("X-App-Id", equalTo("PORTAL_01")));
// 2. Assert zero calls reached unapproved endpoints:
verify(0, deleteRequestedFor(anyUrl()));
// 3. Extract all received requests for granular assertions:
List<LoggedRequest> recordedRequests = findAll(postRequestedFor(urlEqualTo("/api/v1/audit/log")));
assertEquals(2, recordedRequests.size());
String firstPayload = recordedRequests.get(0).getBodyAsString();
assertTrue(firstPayload.contains("LOGIN_SUCCESS"));
}
}
package com.nikitainfotech.api.wiremock;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.wiremock.webhooks.Webhooks.webhook;
@WireMockTest(httpPort = 8089)
public class WireMockWebhookSimulationTest {
@Test
public void testAsynchronousWebhookCallback() {
// Configure stub to return 202 Accepted and trigger an asynchronous webhook POST callback
stubFor(post("/api/v1/orders/checkout")
.willReturn(aResponse()
.withStatus(202)
.withBody("{\"orderId\":\"ORD-88192\",\"status\":\"PROCESSING\"}"))
// PostServeAction: Fires out-of-band webhook back to application callback listener
.withPostServeAction("webhook", webhook()
.withMethod(com.github.tomakehurst.wiremock.http.RequestMethod.POST)
.withUrl("http://localhost:8089/api/v1/webhooks/order-fulfilled")
.withHeader("Content-Type", "application/json")
.withHeader("X-Signature", "hmac_sha256_valid_sig")
.withBody("{"
+ "\"orderId\":\"ORD-88192\","
+ "\"event\":\"PAYMENT_SETTLED\","
+ "\"settledTimestamp\":1793529000"
+ "}")));
// Stub the callback receiver endpoint
stubFor(post("/api/v1/webhooks/order-fulfilled")
.willReturn(aResponse().withStatus(200)));
// 1. Application calls checkout endpoint
RestAssured.given().baseUri("http://localhost:8089")
.body("{\"orderId\":\"ORD-88192\",\"amount\":14999.00}")
.post("/api/v1/orders/checkout")
.then()
.statusCode(202);
// 2. Wait briefly and assert WireMock fired the asynchronous webhook callback
try { Thread.sleep(500); } catch (InterruptedException ignored) {}
verify(1, postRequestedFor(urlEqualTo("/api/v1/webhooks/order-fulfilled"))
.withHeader("X-Signature", equalTo("hmac_sha256_valid_sig"))
.withRequestBody(containing("PAYMENT_SETTLED")));
}
}
/__admin/ namespace, allowing test frameworks in Python, Node.js, or cURL to register stubs, inspect logs, and reset mappings dynamically over HTTP.
# 1. Register a fresh stub mapping dynamically via HTTP POST
curl -s -X POST "http://localhost:8089/__admin/mappings" \
-H "Content-Type: application/json" \
-d '{
"request": {
"method": "GET",
"url": "/api/v1/dynamic-course"
},
"response": {
"status": 200,
"jsonBody": { "code": "REST-99", "title": "Admin API Injected Stub" }
}
}'
# 2. Retrieve all active stub mappings currently registered in WireMock
curl -s -X GET "http://localhost:8089/__admin/mappings" | jq .
# 3. Retrieve request journal of all received wire interactions
curl -s -X GET "http://localhost:8089/__admin/requests" | jq .
# 4. Reset request journal (clears received history without removing stubs)
curl -s -X POST "http://localhost:8089/__admin/requests/reset"
# 5. Full Reset: Purge all stubs and return WireMock to default state
curl -s -X POST "http://localhost:8089/__admin/reset"
# 6. Shut down running standalone WireMock daemon remotely
curl -s -X POST "http://localhost:8089/__admin/shutdown"
WIREMOCK CAPABILITIES & CONFIGURATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββββββ
β DIRECTIVE / METHOD β USAGE CONTEXT β PRIMARY PURPOSE & BEHAVIOR β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββββββββ€
β wiremockConfig().dyn.. β JUnit 5 WireMockExtension β Assigns random free TCP port to avoid collisions β
β stubFor(get(urlEqualTo))β Java DSL Programmatic Stub β Registers URL, header, and body mapping criteria β
β mappings/*.json β Standalone / Docker root-dir β Declarative JSON stub definitions on disk β
β __files/* β Standalone / Docker root-dir β Externalized large/binary response body payloads β
β response-template β Transformers β Handlebars {{jsonPath}} dynamic parameter echo β
β inScenario().whenState..β Java DSL / JSON Descriptor β Stateful finite state machine for retry testing β
β withFault(Fault.CONN..) β Chaos Engineering β Injects socket drops, packet resets, junk bytes β
β proxiedFrom(backendUrl) β Reverse Proxy Mode β Forwards un-stubbed traffic to live backend API β
β verify(count, reqSpec) β Test Assertions β Asserts exact number of wire requests received β
β /__admin/mappings β REST Management API β Registers and queries stubs over HTTP β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββ€
β TOP 5 WIREMOCK ENTERPRISE BEST PRACTICES: β
β 1. Always use dynamicPort() in JUnit 5: Prevents port binding failures across concurrent CI builds. β
β 2. Reset between tests: Use wm.resetAll() in @AfterEach to ensure test isolation. β
β 3. Externalize large payloads to __files/: Keeps mapping JSON descriptors compact and maintainable. β
β 4. Leverage priority for selective proxying: Stub target routes at priority 1, proxy the rest at 10. β
β 5. Verify interaction counts: Use verify() to confirm your application actually invoked the mock. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ