π Service Virtualization, Hermetic Test Execution & Chaos Engineering
In microservice architectures and automated CI/CD pipelines, executing API integration tests against live downstream dependenciesβsuch as third-party payment gateways, external identity providers, or partner messaging APIsβintroduces flaky test failures, rate-limiting locks, test data corruption, and high infrastructure costs. Furthermore, testing edge cases like network timeouts, 503 Service Unavailable outages, and TCP socket resets is nearly impossible against live production or shared staging environments. WireMock provides an enterprise HTTP mock server and service virtualization solution. Whether running as a standalone Docker container or directly embedded inside Java test runners using WireMockServer, WireMock intercepts HTTP wire requests from REST Assured, matches headers, paths, and payloads, returns mock JSON/XML responses, simulates latency, and verifies outbound request invocations. This guarantees completely isolated, reproducible, and deterministic test executions.
WIREMOCK EMBEDDED VS. STANDALONE SERVICE VIRTUALIZATION ARCHITECTURE:
1. EMBEDDED IN-PROCESS JVM ARCHITECTURE (Ideal for Unit/Component Integration Suites):
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SINGLE JVM PROCESS (TestNG / JUnit 5 Test Runner) β
β β
β βββββββββββββββββββββββββββββββββββββββββββ HTTP Socket Dispatch (localhost:dynamicPort) β
β β REST Assured Test Suite ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β given().baseUri(mockServer.baseUrl())...β β β
β βββββββββββββββββββββββββββββββββββββββββββ βΌ β
β β (Configures Stubs In-Memory via Java DSL) βββββββββββββββββββ β
β βββββββββββββββββββββββββββββββββββββββββββββββββββΊβ WireMockServer β β
β β (Jetty Server) β β
β βββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
2. STANDALONE CONTAINER / OUT-OF-PROCESS ARCHITECTURE (Ideal for E2E / Shared Environments):
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β TEST WORKER MACHINE (CI/CD Runner) β β DOCKER CONTAINER / KUBERNETES POD β
β REST Assured Pipeline β β wiremock/wiremock:3.5.2 (Port: 8080) β
β βββ POST http://wiremock:8080/__admin/stubs βββββββΊβ βββ WireMock Admin API REST Controller β
β βββ Dispatches business API tests to stubs ββββββββ βββ In-Memory Mapping Registry (__files/) β
β β β βββ Request Journal & Matcher Engine β
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
WireMockServer inside a TestNG base class. Demonstrates dynamic port binding, global stub registration, base URI injection into REST Assured, and graceful server shutdown.
package com.nikita.restassured.wiremock;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
public abstract class WireMockBaseTest {
protected static WireMockServer wireMockServer;
protected static RequestSpecification mockSpec;
@BeforeSuite(alwaysRun = true)
public void startGlobalWireMock() {
// Configure WireMock to bind to an available dynamic ephemeral port:
wireMockServer = new WireMockServer(WireMockConfiguration.options().dynamicPort());
wireMockServer.start();
// Configure static client to direct WireMock DSL commands to this server instance:
WireMock.configureFor("localhost", wireMockServer.port());
System.out.printf("[*] WireMockServer started successfully on dynamic port: %d (Base URL: %s)%n",
wireMockServer.port(), wireMockServer.baseUrl());
// Build base specification pointing to the embedded mock server
mockSpec = new RequestSpecBuilder()
.setBaseUri(wireMockServer.baseUrl())
.setContentType(ContentType.JSON)
.setAccept(ContentType.JSON)
.build();
}
@BeforeClass(alwaysRun = true)
public void resetStubs() {
// Reset stubs and request journals between test classes to ensure clean state
wireMockServer.resetAll();
System.out.println("[*] WireMock mappings and request journal reset.");
}
@AfterSuite(alwaysRun = true)
public void stopGlobalWireMock() {
if (wireMockServer != null && wireMockServer.isRunning()) {
wireMockServer.stop();
System.out.println("[*] WireMockServer stopped successfully.");
}
}
}
package com.nikita.restassured.wiremock;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class BasicStubbingTest extends WireMockBaseTest {
@Test(description = "Stub GET /v1/students/{id} and verify via REST Assured")
public void testStubbedGetStudent() {
// 1. DEFINE WIREMOCK STUB
stubFor(get(urlEqualTo("/v1/students/STU-88219"))
.withHeader("Accept", containing("application/json"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json; charset=utf-8")
.withHeader("X-Mocked-By", "WireMock-Masterclass")
.withBody("{\n" +
" \"status\": \"SUCCESS\",\n" +
" \"data\": {\n" +
" \"id\": \"STU-88219\",\n" +
" \"fullName\": \"Nikita Sharma\",\n" +
" \"academicTrack\": \"ENTERPRISE_AUTOMATION\",\n" +
" \"enrolledCredits\": 16\n" +
" }\n" +
"}")));
// 2. DISPATCH CALL VIA REST ASSURED TO MOCK SERVER
given()
.spec(mockSpec)
.when()
.get("/v1/students/STU-88219")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.header("X-Mocked-By", equalTo("WireMock-Masterclass"))
.body("status", equalTo("SUCCESS"))
.body("data.id", equalTo("STU-88219"))
.body("data.fullName", equalTo("Nikita Sharma"));
System.out.println("[β] GET stub matched successfully and returned mock response.");
}
@Test(description = "Stub POST with matching body regex criteria")
public void testStubbedPostStudent() {
// Stub POST with JSON body pattern matching
stubFor(post(urlPathEqualTo("/v1/students"))
.withHeader("Content-Type", containing("application/json"))
.withRequestBody(matchingJsonPath("$.[?(@.enrolledCredits >= 12)]"))
.willReturn(aResponse()
.withStatus(201)
.withHeader("Content-Type", "application/json")
.withBody("{\"status\": \"CREATED\", \"id\": \"STU-99412\"}")));
given()
.spec(mockSpec)
.body("{\"fullName\": \"Aarav Deshmukh\", \"enrolledCredits\": 16}")
.when()
.post("/v1/students")
.then()
.statusCode(201)
.body("status", equalTo("CREATED"))
.body("id", equalTo("STU-99412"));
System.out.println("[β] POST stub matched with matchingJsonPath rule.");
}
}
withFixedDelay() or dynamic random distribution delays to verify client timeout policies and REST Assured latency assertions.
package com.nikita.restassured.wiremock;
import org.testng.annotations.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThan;
public class LatencySimulationTest extends WireMockBaseTest {
@Test(description = "Simulate 800ms backend latency and assert REST Assured SLA response time")
public void testSimulatedLatencyResponseTime() {
// Configure stub to pause for exactly 800ms before returning bytes:
stubFor(get(urlEqualTo("/v1/analytics/aggregate"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withFixedDelay(800) // Fixed delay in milliseconds
.withBody("{\"reportStatus\": \"COMPLETED\", \"metrics\": {\"processed\": 450}}")));
long startEpoch = System.currentTimeMillis();
given()
.spec(mockSpec)
.when()
.get("/v1/analytics/aggregate")
.then()
.statusCode(200)
// Assert response time falls within expected bounds (>= 800ms and < 2000ms):
.time(greaterThanOrEqualTo(800L))
.time(lessThan(2500L));
long elapsedMs = System.currentTimeMillis() - startEpoch;
System.out.printf("[β] Latency simulation verified: Total elapsed round-trip was %d ms.%n", elapsedMs);
}
}
Fault constructsβFault.EMPTY_RESPONSE, Fault.MALFORMED_RESPONSE_CHUNK, and Fault.RANDOM_DATA_THEN_CLOSEβto test client resilience and error handling.
package com.nikita.restassured.wiremock;
import com.github.tomakehurst.wiremock.http.Fault;
import org.testng.Assert;
import org.testng.annotations.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
public class FaultInjectionChaosTest extends WireMockBaseTest {
@Test(description = "Verify client resilience when WireMock abruptly drops connection (EMPTY_RESPONSE)")
public void testEmptyResponseFaultInjection() {
// Stub endpoint to close TCP socket immediately without sending any HTTP response bytes:
stubFor(get(urlEqualTo("/v1/chaos/connection-drop"))
.willReturn(aResponse()
.withFault(Fault.EMPTY_RESPONSE)));
try {
given()
.spec(mockSpec)
.when()
.get("/v1/chaos/connection-drop");
Assert.fail("Expected connection exception when server drops socket abruptly!");
} catch (Exception e) {
System.out.println("[β] Successfully intercepted expected socket failure: " + e.getClass().getSimpleName());
Assert.assertTrue(e.getMessage().contains("target host failed to respond")
|| e.getMessage().contains("Connection reset")
|| e.getMessage().contains("Premature end of Content-Length delimited message"));
}
}
@Test(description = "Verify client resilience when WireMock transmits garbage bytes (RANDOM_DATA_THEN_CLOSE)")
public void testRandomGarbageBytesFault() {
// Stub endpoint to send random non-HTTP garbage bytes and terminate socket:
stubFor(get(urlEqualTo("/v1/chaos/garbage-stream"))
.willReturn(aResponse()
.withFault(Fault.RANDOM_DATA_THEN_CLOSE)));
try {
given()
.spec(mockSpec)
.when()
.get("/v1/chaos/garbage-stream");
Assert.fail("Expected protocol exception on garbage byte stream!");
} catch (Exception e) {
System.out.println("[β] Client gracefully detected malformed protocol bytes: " + e.getMessage());
}
}
}
package com.nikita.restassured.wiremock;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class ResponseTemplatingTest {
private WireMockServer templatedServer;
private RequestSpecification templatedSpec;
@BeforeClass
public void setupTemplatedServer() {
// Enable ResponseTemplateTransformer extension to process Handlebars tokens:
templatedServer = new WireMockServer(WireMockConfiguration.options()
.dynamicPort()
.extensions(new ResponseTemplateTransformer(true)));
templatedServer.start();
WireMock.configureFor("localhost", templatedServer.port());
templatedSpec = new RequestSpecBuilder()
.setBaseUri(templatedServer.baseUrl())
.setContentType(ContentType.JSON)
.build();
// Stub extracting request.path.[1] and request.query.format:
templatedServer.stubFor(get(urlPathMatching("/v1/echo/([a-zA-Z0-9_-]+)"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\n" +
" \"echoedId\": \"{{request.path.[2]}}\",\n" +
" \"requestedTier\": \"{{request.query.tier}}\",\n" +
" \"generatedEpoch\": \"{{now}}\"\n" +
"}")));
}
@Test(description = "Verify WireMock dynamic Handlebars response templating echoes query parameters")
public void testDynamicHandlebarsEcho() {
given()
.spec(templatedSpec)
.queryParam("tier", "ENTERPRISE_VIP")
.when()
.get("/v1/echo/STU-88219")
.then()
.statusCode(200)
.body("echoedId", equalTo("STU-88219"))
.body("requestedTier", equalTo("ENTERPRISE_VIP"));
System.out.println("[β] Handlebars template dynamically synthesized response from request metadata.");
}
@AfterClass(alwaysRun = true)
public void teardownServer() {
if (templatedServer != null) {
templatedServer.stop();
}
}
}
verify() to assert that REST Assured dispatched the expected number of calls, verified required headers, and transmitted compliant request bodies.
package com.nikita.restassured.wiremock;
import org.testng.annotations.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
public class RequestVerificationTest extends WireMockBaseTest {
@Test(description = "Audit that outbound call was transmitted exactly once with required tracing header")
public void testVerifyRequestContract() {
// Stub endpoint
stubFor(delete(urlEqualTo("/v1/students/STU-88219"))
.willReturn(aResponse().withStatus(204)));
// Dispatch DELETE call via REST Assured
given()
.spec(mockSpec)
.header("X-Correlation-Id", "TRACE-REQ-AUDIT-99")
.when()
.delete("/v1/students/STU-88219")
.then()
.statusCode(204);
// =============================================================
// WIREMOCK AUDIT VERIFICATION: Confirm call arrived at mock server
// =============================================================
verify(exactly(1), deleteRequestedFor(urlEqualTo("/v1/students/STU-88219"))
.withHeader("X-Correlation-Id", equalTo("TRACE-REQ-AUDIT-99")));
// Verify that NO calls were made to other endpoints
verify(exactly(0), postRequestedFor(urlEqualTo("/v1/students")));
System.out.println("[β] WireMock verification audit passed: Call occurred exactly 1 time with tracing header.");
}
}
mappings/ for stub rules, __files/ for response bodies) to load complex mocks from version control.
# ==============================================================================
# 1. DIRECTORY STRUCTURE REQUIRED IN src/test/resources/
# ==============================================================================
# src/test/resources/
# βββ mappings/
# β βββ get-student-profile.json βββΊ Defines matching rules and status
# βββ __files/
# βββ student-profile-mock.json βββΊ Large static JSON response body
# ==============================================================================
# 2. STUB DEFINITION: src/test/resources/mappings/get-student-profile.json
# ==============================================================================
{
"request": {
"method": "GET",
"urlPathPattern": "/v1/external/students/[0-9]+"
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json; charset=utf-8"
},
"bodyFileName": "student-profile-mock.json"
}
}
# ==============================================================================
# 3. RESPONSE BODY: src/test/resources/__files/student-profile-mock.json
# ==============================================================================
{
"studentId": "STU-88219",
"fullName": "Nikita Sharma",
"academicTrack": "ENTERPRISE_AUTOMATION",
"verifiedBy": "WireMock-Filesystem-Loader"
}
package com.nikita.restassured.wiremock;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import io.restassured.http.ContentType;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class FilesystemMappingsTest {
private WireMockServer fileServer;
@BeforeClass
public void setupFileServer() {
// Configure WireMock to read mappings and __files from classpath resources:
fileServer = new WireMockServer(WireMockConfiguration.options()
.dynamicPort()
.usingFilesUnderClasspath("")); // Root classpath contains mappings/ and __files/
fileServer.start();
}
@Test(description = "Verify endpoint mapped purely via JSON configuration file on classpath")
public void testFileMappedEndpoint() {
given()
.baseUri(fileServer.baseUrl())
.accept(ContentType.JSON)
.when()
.get("/v1/external/students/88219")
.then()
.statusCode(200)
.body("fullName", equalTo("Nikita Sharma"))
.body("verifiedBy", equalTo("WireMock-Filesystem-Loader"));
System.out.println("[β] Loaded stub mapping and body seamlessly from classpath resources.");
}
@AfterClass(alwaysRun = true)
public void teardown() {
if (fileServer != null) {
fileServer.stop();
}
}
}
HTTP 404 Not Found when stub patterns don't match, and demonstrates how to inspect WireMock's diagnostic diffs to spot subtle URL, header, or body mismatches.
package com.nikita.restassured.wiremock;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import org.testng.annotations.Test;
import java.util.List;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
public class WireMockTriageTest extends WireMockBaseTest {
// ==========================================================================
// ANATOMY OF A WIREMOCK 404 "UNMATCHED REQUEST" ERROR
// When a request returns 404 from WireMock, it means NO stub matched the
// exact combination of HTTP method, URL pattern, headers, and body!
// WireMock outputs a line-by-line diff showing where expectations diverged.
// ==========================================================================
@Test(description = "Demonstrate inspection of unmatched requests in WireMock journal")
public void testInspectUnmatchedRequests() {
// Stub configured with strict header requirement
stubFor(get(urlEqualTo("/v1/secure/resource"))
.withHeader("X-Mandatory-Key", equalTo("REQUIRED_SECRET"))
.willReturn(aResponse().withStatus(200)));
// Request intentionally dispatched WITHOUT the required header (causes 404):
given()
.spec(mockSpec)
.when()
.get("/v1/secure/resource")
.then()
.statusCode(404); // WireMock returns 404 for unmatched requests!
// Query unmatched requests from WireMock journal for debugging:
List<LoggedRequest> unmatchedRequests = wireMockServer.findAllUnmatchedRequests();
System.out.println("Total unmatched requests recorded: " + unmatchedRequests.size());
for (LoggedRequest req : unmatchedRequests) {
System.out.println("Unmatched Method : " + req.getMethod());
System.out.println("Unmatched URL : " + req.getUrl());
System.out.println("Unmatched Headers: " + req.getHeaders());
}
}
// ==========================================================================
// DIAGNOSTIC DIFF GENERATED BY WIREMOCK IN CONSOLE:
// ==========================================================================
// Request was not matched:
// {
// "url" : "/v1/secure/resource",
// "method" : "GET",
// "headers" : { ... }
// }
// Closest stub match:
// {
// "url" : "/v1/secure/resource",
// "method" : "GET",
// "headers" : {
// "X-Mandatory-Key" : { "equalTo" : "REQUIRED_SECRET" } <<<<< Header was missing!
// }
// }
}
WIREMOCK SPECIFICATION & STUBBING REFERENCE MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β WIREMOCK CONSTRUCT β DSL SYNTAX EXAMPLE β PARAMETER TYPE β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Dynamic Port Config β options().dynamicPort() β WireMockConfig β Ephemeral port allocation β
β URL Exact Match β urlEqualTo("/path/to/res") β UrlPattern β Exact string path matching β
β URL Regex Match β urlPathMatching("/v1/.*") β UrlPattern β Regex path matching β
β Header Matching β withHeader("Key", equalTo()) β ValuePattern β Inbound header assertion β
β Body JSONPath Match β withRequestBody(matching.. β JSONPath Matcher β Payload predicate matching β
β Fixed Latency Delay β aResponse().withFixedDelay(n)β int milliseconds β Simulates backend latency β
β Random Latency Delay β withLogNormalRandomDelay(..) β Distribution β Simulates jitter / lag spikes β
β Fault: Empty Response β withFault(Fault.EMPTY_RESP) β Fault Enum β Drops socket with zero bytes β
β Fault: Malformed Chunk β withFault(Fault.MALFORMED..) β Fault Enum β Sends broken chunked packets β
β Fault: Garbage Stream β withFault(Fault.RANDOM_DATA) β Fault Enum β Sends random bytes & closes β
β Handlebars Templating β {{request.query.paramName}} β Template Token β Echoes dynamic request values β
β Filesystem Loader β usingFilesUnderClasspath("") β Path String β Loads mappings/ and __files/ β
β Outbound Verification β verify(count, requestFor()) β Verification β Audits client call count β
β Server Reset β wireMockServer.resetAll() β Cleanup Method β Clears stubs between tests β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 WIREMOCK BEST PRACTICES: β
β 1. Always use dynamicPort(): Prevent port binding collisions in parallel TestNG / CI/CD executions. β
β 2. Reset stubs in @BeforeMethod: Ensure tests run against clean mappings without order dependencies. β
β 3. Test edge-case timeouts via withFixedDelay(): Validate client socket timeout limits deterministically β
β 4. Test error handling via Fault injection: Verify client behavior when connections drop unexpectedly. β
β 5. Audit interactions via verify(): Confirm that client requests send required correlation headers. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ