WIREMOCK STANDALONE & SETUP: EMBEDDED SERVERS, STUBBING & FAULT INJECTION

Architect hermetic, isolated API virtualization in REST Assured: Standalone WireMock vs. embedded WireMockServer, TestNG @BeforeSuite/@BeforeMethod lifecycle management, dynamic port binding via dynamicPort(), fluent DSL stubbing (urlEqualTo, urlPathMatching), JSON response templating, simulated network delays, HTTP fault injection (bad responses, malformed headers, socket drops), and request verification audits.

🌐 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.

1. Standalone vs. Embedded WireMock Architecture & Lifecycle Topography
The architectural topologies of WireMock deployment models: Embedded in-process JVM execution with dynamic port allocation versus standalone containerized mock server instances.
WireMock Deployment Topology: Embedded vs. Standalone Mocking
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        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: For fast, hermetic test suites, prefer embedded WireMockServer instances bound to dynamicPort(). Dynamic port allocation allows multiple parallel TestNG worker threads to spin up isolated WireMock servers on free ephemeral ports simultaneously with zero port collision.
Real-Time Example 1: Embedded WireMockServer Lifecycle in TestNG (@BeforeSuite / @AfterSuite)
Spinning up an embedded WireMockServer inside a TestNG base class. Demonstrates dynamic port binding, global stub registration, base URI injection into REST Assured, and graceful server shutdown.
Java (WireMockBaseTest.java Embedded Server Lifecycle)
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.");
        }
    }
}
Lifecycle Execution Telemetry: [*] WireMockServer started successfully on dynamic port: 52419 (Base URL: http://localhost:52419) [*] WireMock mappings and request journal reset. Tests dispatch calls to http://localhost:52419 with zero dependencies on live network servers.
Real-Time Example 2: Fluent Stubbing with WireMock Java DSL (GET, POST, Headers & Query Params)
Creating dynamic HTTP stubs using the fluent WireMock DSL. Configures exact URL matching, path regexes, query parameter filters, request header verifications, and custom mock response bodies.
Java (Fluent Stub Definition & REST Assured Verification)
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.");
    }
}
Stubbing Execution Output: GET http://localhost:52419/v1/students/STU-88219 -> HTTP 200 OK [18ms] Headers: Content-Type=application/json; charset=utf-8, X-Mocked-By=WireMock-Masterclass POST http://localhost:52419/v1/students -> HTTP 201 Created [12ms] Payload verified: $.status == "CREATED", $.id == "STU-99412" PASSED: testStubbedGetStudent PASSED: testStubbedPostStudent
Real-Time Example 3: Simulating Network Latency, Delays & SLA Testing
Testing performance and timeout thresholds. Configures fixed delays via withFixedDelay() or dynamic random distribution delays to verify client timeout policies and REST Assured latency assertions.
Java (Simulating Network Delays & SLA Timeouts)
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);
    }
}
Latency Simulation Output: GET http://localhost:52419/v1/analytics/aggregate -> HTTP 200 OK [Elapsed: 824ms] SLA assertion verified: 824ms >= 800ms and < 2500ms Enables reliable verification of client socket timeouts and retry middleware without third-party network proxies.
Real-Time Example 4: Fault Injection: Malformed Responses, Empty Byte Arrays & Socket Drops
Simulating chaotic failure conditions. Uses WireMock's Fault constructsβ€”Fault.EMPTY_RESPONSE, Fault.MALFORMED_RESPONSE_CHUNK, and Fault.RANDOM_DATA_THEN_CLOSEβ€”to test client resilience and error handling.
Java (WireMock Fault Injection & Chaos Engineering)
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());
        }
    }
}
Fault Injection Telemetry: [βœ”] Successfully intercepted expected socket failure: NoHttpResponseException (target host failed to respond) [βœ”] Client gracefully detected malformed protocol bytes: org.apache.http.ProtocolException Chaos testing confirms that custom client retry logic and circuit breakers handle transport-level socket drops correctly.
Real-Time Example 5: Dynamic Response Templating via Handlebars (request.path / request.query)
Echoing request data back in mock responses. Enables response templating in WireMock using Handlebars to dynamically insert request parameters, headers, or body nodes into the returned mock JSON.
Java (WireMock Dynamic Response Templating via Handlebars)
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();
        }
    }
}
Templating Execution Trace: GET http://localhost:53120/v1/echo/STU-88219?tier=ENTERPRISE_VIP -> HTTP 200 OK [14ms] Response payload returned: { "echoedId": "STU-88219", "requestedTier": "ENTERPRISE_VIP", "generatedEpoch": "2026-11-03T10:45:00Z" } Dynamic templates avoid maintaining dozens of static mock files for each scenario.
Real-Time Example 6: Auditing Request Invocations with verify() & Find Requests
Verifying outbound interaction contracts. Uses verify() to assert that REST Assured dispatched the expected number of calls, verified required headers, and transmitted compliant request bodies.
Java (WireMock Inbound Request Audit via verify())
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.");
    }
}
Verification Audit Output: DELETE /v1/students/STU-88219 -> HTTP 204 No Content verify(exactly(1), deleteRequestedFor(...)) ──► PASSED (1 matching request in journal) verify(exactly(0), postRequestedFor(...)) ──► PASSED (0 matching requests in journal) Confirms not only response behavior, but also that clients adhere to expected outbound contracts.
Real-Time Example 7: Loading Static Stubs from JSON Files (__files & mappings)
Organizing static stubs without Java code. Uses WireMock's standard filesystem mapping directory structure (mappings/ for stub rules, __files/ for response bodies) to load complex mocks from version control.
JSON Mapping & Body Files: mappings/ & __files/ Directory Setup
# ==============================================================================
# 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"
}
Java (Executing Test with Filesystem-Loaded Mappings)
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();
        }
    }
}
Filesystem Stub Output: GET http://localhost:54890/v1/external/students/88219 -> HTTP 200 OK [11ms] Body read from: src/test/resources/__files/student-profile-mock.json Allows frontend and QA teams to curate mock responses as standalone JSON files.
Real-Time Example 8: Debugging WireMock 404s & Unmatched Request Diff Triage
Troubleshooting stub matching failures. Explains why WireMock returns 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.
Java (Triage: Diagnosing Unmatched Request Diffs)
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!
    //   }
    // }
}
Triage Diagnostic Breakdown: - WireMock 404 indicates a stub mismatch, NOT a missing backend endpoint. - Closest stub comparison highlights missing header: X-Mandatory-Key == REQUIRED_SECRET. - WireMock request journal logs unparsed requests to speed up troubleshooting.
Real-Time Example 9: WireMock Specification Reference Matrix
A comprehensive reference summary pairing WireMock methods, configuration builders, stubbing criteria, fault types, and operational best practices for REST Assured automation architects.
WireMock Specification Reference Matrix
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.       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: WireMock service virtualization provides complete control over external HTTP dependencies. By pairing embedded WireMockServer instances on dynamic ports with REST Assured, injecting latency and transport-level faults, and auditing outbound interactions via verify(), you build fast, hermetic API test automation frameworks that run reliably without depending on live external services.