WIREMOCK FAULT INJECTION & DELAYS: SOCKET CORRUPTIONS & RESILIENCE TESTING

Architect production-grade chaos engineering and network degradation tests in REST Assured: TCP-level fault injection (EMPTY_RESPONSE, RANDOM_DATA_THEN_CLOSE, MALFORMED_RESPONSE_CHUNK, PEER_CONNECTION_RESET_BY_PEER), fixed latency ceilings, LogNormal and uniform random jitter distributions, Apache HttpClient socket timeout validations, and client circuit breaker verification.

⚑ Chaos Engineering, Transport Failures & Resilience Hardening

Verifying an application's behavior under pristine network conditions covers only the sunny path. In distributed cloud environments and Kubernetes clusters, microservices routinely encounter transport-level network disruptions: socket drops mid-transmission, hung TCP handshakes, intermittent latency spikes (jitter), malformed packet chunks, and sudden connection resets (RST packets). Attempting to validate client-side timeout configurations, retry policies, or circuit breakers against live APIs is unsafe and untestable. WireMock's Fault Injection and Latency Simulation Engine enables controlled chaos testing directly inside your automation suite. By manipulating com.github.tomakehurst.wiremock.http.Fault and statistical distribution models (such as LogNormal and uniform jitter) in conjunction with REST Assured, test engineers verify that client timeout bounds fail fast, retry loops prevent cascading failures, and downstream outages are isolated gracefully.

1. WireMock Transport Fault & Latency Distribution Topography
The architectural taxonomy of transport-layer network failures in WireMock, showing how HTTP sockets are corrupted, truncated, or delayed before and during transmission to REST Assured.
Fault Injection & Latency Simulation Topography
WIREMOCK TRANSPORT-LEVEL CHAOS & LATENCY INJECTION ARCHITECTURE:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ REST ASSURED CLIENT (Apache HttpClient Socket Transport Layer)                                β”‚
β”‚ Timeout Thresholds: connectTimeout = 2000ms | socketTimeout = 3000ms                          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό (Dispatches HTTP Request over Loopback Socket)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ WIREMOCK EMBEDDED SERVER INTERCEPTOR ENGINE                                                   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                     β–Ό                                                     β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ FAULT INJECTION (TCP SOCKET CORRUPTION)      β”‚      β”‚ LATENCY & JITTER SIMULATION                  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€      β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 1. Fault.EMPTY_RESPONSE                      β”‚      β”‚ 1. Fixed Latency Delay:                      β”‚
β”‚    β€’ Closes socket with zero HTTP bytes      β”‚      β”‚    β€’ withFixedDelay(2500)                    β”‚
β”‚    β€’ Triggers NoHttpResponseException        β”‚      β”‚ 2. Statistical LogNormal Distribution:       β”‚
β”‚ 2. Fault.RANDOM_DATA_THEN_CLOSE              β”‚      β”‚    β€’ withLogNormalRandomDelay(median, sigma) β”‚
β”‚    β€’ Emits garbage binary octets             β”‚      β”‚    β€’ Models long-tail 99th percentile lag    β”‚
β”‚    β€’ Triggers MalformedChunkCodingException  β”‚      β”‚ 3. Uniform Jitter Distribution:              β”‚
β”‚ 3. Fault.PEER_CONNECTION_RESET_BY_PEER       β”‚      β”‚    β€’ withUniformRandomDelay(100, 800)        β”‚
β”‚    β€’ Emits TCP RST packet mid-stream         β”‚      β”‚ 4. Chunked Dribble Delay:                    β”‚
β”‚ 4. Fault.MALFORMED_RESPONSE_CHUNK            β”‚      β”‚    β€’ withChunkedDribbleDelay(chunks, totalMs)β”‚
β”‚    β€’ Corrupts Transfer-Encoding chunk frames β”‚      β”‚    β€’ Delivers payload byte-by-byte slowly    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ CLIENT RESILIENCE VERIFICATION: Assert exceptions, fallback circuits & retry interceptors     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: WireMock faults operate below the HTTP layer. Rather than returning status codes like 500 or 503, they manipulate raw TCP sockets. This enables genuine chaos testing for low-level connection timeouts and socket exceptions in client applications.
Real-Time Example 1: TCP Connection Dropped Mid-Flight via Fault.EMPTY_RESPONSE
Simulating an abrupt server socket termination. Injects Fault.EMPTY_RESPONSE to close the TCP connection immediately without sending any response headers or bytes, verifying that the client catches NoHttpResponseException.
Java (Fault.EMPTY_RESPONSE Socket Drop Verification)
package com.nikita.restassured.wiremock.faults;

import com.github.tomakehurst.wiremock.http.Fault;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import org.apache.http.NoHttpResponseException;
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 EmptyResponseFaultTest extends WireMockBaseTest {

    @Test(description = "Verify client resilience when WireMock drops TCP connection via EMPTY_RESPONSE")
    public void testEmptyResponseSocketDrop() {
        // Configure stub to accept connection and immediately sever socket with 0 bytes:
        stubFor(get(urlEqualTo("/v1/payments/charge"))
                .willReturn(aResponse()
                        .withFault(Fault.EMPTY_RESPONSE)));

        try {
            given()
                .spec(mockSpec)
            .when()
                .get("/v1/payments/charge");

            Assert.fail("Expected transport failure on dropped socket, but request completed!");
        } catch (Exception e) {
            System.out.println("[βœ”] Intercepted expected socket exception: " + e.getClass().getName());
            System.out.println("    Message: " + e.getMessage());

            // Validate root cause is an abrupt termination (NoHttpResponseException or SocketException)
            boolean isDroppedSocket = e.getMessage().contains("failed to respond") ||
                                      e.getMessage().contains("Connection reset") ||
                                      e.getCause() instanceof NoHttpResponseException;

            Assert.assertTrue(isDroppedSocket, "Exception must indicate an abrupt server disconnect!");
        }
    }
}
Execution Output: GET http://localhost:52419/v1/payments/charge -> Socket disconnected [βœ”] Intercepted expected socket exception: org.apache.http.NoHttpResponseException Message: localhost:52419 failed to respond PASSED: testEmptyResponseSocketDrop
Real-Time Example 2: Corrupted Binary Garbage Stream via Fault.RANDOM_DATA_THEN_CLOSE
Testing protocol parser hardening. Injects Fault.RANDOM_DATA_THEN_CLOSE to send non-HTTP random garbage octets over the wire, verifying that the client detects malformed protocol bytes and prevents invalid state transitions.
Java (Fault.RANDOM_DATA_THEN_CLOSE Garbage Octet Stream)
package com.nikita.restassured.wiremock.faults;

import com.github.tomakehurst.wiremock.http.Fault;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import org.apache.http.ProtocolException;
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 RandomDataFaultTest extends WireMockBaseTest {

    @Test(description = "Verify client rejects malformed non-HTTP random byte stream")
    public void testRandomDataGarbageStream() {
        // WireMock sends random junk bytes then severs the socket
        stubFor(get(urlEqualTo("/v1/students/corrupted-stream"))
                .willReturn(aResponse()
                        .withFault(Fault.RANDOM_DATA_THEN_CLOSE)));

        try {
            given()
                .spec(mockSpec)
            .when()
                .get("/v1/students/corrupted-stream");

            Assert.fail("Expected protocol violation exception on random garbage byte stream!");
        } catch (Exception e) {
            System.out.println("[βœ”] Protocol parsing exception intercepted: " + e.getClass().getSimpleName());
            System.out.println("    Diagnostic Detail: " + e.getMessage());

            // Verify the client correctly rejects invalid HTTP stream data
            Assert.assertNotNull(e.getMessage());
        }
    }
}
Garbage Stream Telemetry: GET http://localhost:52419/v1/students/corrupted-stream -> Random bytes transmitted [βœ”] Protocol parsing exception intercepted: ProtocolException Diagnostic Detail: The server failed to respond with a valid HTTP response PASSED: testRandomDataGarbageStream
Real-Time Example 3: Chunked Transfer Coding Corruptions via Fault.MALFORMED_RESPONSE_CHUNK
Testing chunked transfer reliability. Injects Fault.MALFORMED_RESPONSE_CHUNK to start streaming a Transfer-Encoding: chunked response and intentionally corrupt chunk boundaries mid-payload, triggering chunk parsing failures.
Java (Fault.MALFORMED_RESPONSE_CHUNK Frame Corruption)
package com.nikita.restassured.wiremock.faults;

import com.github.tomakehurst.wiremock.http.Fault;
import com.nikita.restassured.wiremock.WireMockBaseTest;
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 MalformedChunkFaultTest extends WireMockBaseTest {

    @Test(description = "Verify client fails fast when response chunk boundaries are corrupted mid-stream")
    public void testMalformedChunkCoding() {
        // Emits initial valid chunk header, then sends malformed framing bytes mid-stream
        stubFor(get(urlEqualTo("/v1/reports/chunked-export"))
                .willReturn(aResponse()
                        .withFault(Fault.MALFORMED_RESPONSE_CHUNK)));

        try {
            given()
                .spec(mockSpec)
            .when()
                .get("/v1/reports/chunked-export");

            Assert.fail("Expected chunk coding corruption exception, but call succeeded!");
        } catch (Exception e) {
            System.out.println("[βœ”] Malformed chunk coding intercepted: " + e.getClass().getSimpleName());
            System.out.println("    Detail: " + e.getMessage());

            boolean isChunkError = e.getMessage().contains("chunk") || 
                                   e.getMessage().contains("Premature end") ||
                                   e.getMessage().contains("Garbage in end of chunk");

            Assert.assertTrue(isChunkError, "Exception must reference chunk decoding failures!");
        }
    }
}
Chunk Corruption Output: GET http://localhost:52419/v1/reports/chunked-export -> Chunk frame header sent, payload corrupted [βœ”] Malformed chunk coding intercepted: MalformedChunkCodingException Detail: Garbage in end of chunk PASSED: testMalformedChunkCoding
Real-Time Example 4: Fixed Latency Simulation vs. HttpClient Socket Timeouts
Verifying client-side timeout thresholds. Configures a withFixedDelay(3500) in WireMock while setting a strict socketTimeout = 2000ms on REST Assured's HttpClientConfig, asserting a SocketTimeoutException occurs.
Java (Testing Socket Timeout Thresholds with Fixed Delays)
package com.nikita.restassured.wiremock.faults;

import com.nikita.restassured.wiremock.WireMockBaseTest;
import io.restassured.config.HttpClientConfig;
import io.restassured.config.RestAssuredConfig;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.net.SocketTimeoutException;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;

public class SocketTimeoutValidationTest extends WireMockBaseTest {

    @Test(description = "Verify client socket timeout fires when WireMock fixed delay exceeds threshold")
    public void testClientSocketTimeoutTriggered() {
        // WireMock pauses for 3500ms before returning response
        stubFor(get(urlEqualTo("/v1/external/slow-endpoint"))
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withFixedDelay(3500) // 3.5-second server delay
                        .withBody("{\"status\": \"LATE_RESPONSE\"}")));

        // Configure strict 1500ms socket timeout on client side:
        RestAssuredConfig strictTimeoutConfig = RestAssuredConfig.config()
                .httpClient(HttpClientConfig.httpClientConfig()
                        .setParam("http.socket.timeout", 1500)       // 1.5s timeout threshold
                        .setParam("http.connection.timeout", 1500));

        long startEpoch = System.currentTimeMillis();

        try {
            given()
                .spec(mockSpec)
                .config(strictTimeoutConfig)
            .when()
                .get("/v1/external/slow-endpoint");

            Assert.fail("Expected SocketTimeoutException, but call completed without timing out!");
        } catch (Exception e) {
            long duration = System.currentTimeMillis() - startEpoch;
            System.out.printf("[βœ”] SocketTimeoutException caught after %d ms (Threshold: 1500ms)%n", duration);
            System.out.println("    Exception Class: " + e.getClass().getName());

            boolean isTimeout = e.getMessage().contains("Read timed out") || 
                                e.getCause() instanceof SocketTimeoutException;

            Assert.assertTrue(isTimeout, "Exception must indicate a read timeout!");
            Assert.assertTrue(duration >= 1400 && duration < 3000, "Timeout must fire close to 1500ms limit!");
        }
    }
}
Socket Timeout Trace: WireMock Fixed Delay: 3500ms | Client Socket Timeout: 1500ms GET http://localhost:52419/v1/external/slow-endpoint -> Paused... [βœ”] SocketTimeoutException caught after 1522 ms (Threshold: 1500ms) Exception Class: java.net.SocketTimeoutException (Read timed out) PASSED: testClientSocketTimeoutTriggered
Real-Time Example 5: Realistic Jitter Simulation via LogNormal & Uniform Distributions
Modeling realistic production network latency. Applies withLogNormalRandomDelay() and withUniformRandomDelay() in WireMock to simulate variable latency spikes and verify client performance across statistical distributions.
Java (Statistical Latency Distributions: LogNormal & Uniform Jitter)
package com.nikita.restassured.wiremock.faults;

import com.nikita.restassured.wiremock.WireMockBaseTest;
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 LatencyDistributionTest extends WireMockBaseTest {

    @Test(description = "Simulate realistic long-tail latency spikes using LogNormal distribution")
    public void testLogNormalLatencyJitter() {
        // LogNormal distribution models real web traffic:
        // Median delay: 300ms, Sigma (spread): 0.4.
        // Most requests complete ~300ms; occasional 99th percentile calls take 800-1200ms.
        stubFor(get(urlEqualTo("/v1/students/search"))
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withLogNormalRandomDelay(300, 0.4)
                        .withBody("{\"results\": [\"STU-88219\", \"STU-99412\"]}")));

        for (int i = 1; i <= 3; i++) {
            long start = System.currentTimeMillis();

            given()
                .spec(mockSpec)
            .when()
                .get("/v1/students/search")
            .then()
                .statusCode(200)
                .time(greaterThanOrEqualTo(100L))
                .time(lessThan(3000L));

            long duration = System.currentTimeMillis() - start;
            System.out.printf("[LogNormal Sample %d] Round-trip latency: %d ms%n", i, duration);
        }
    }

    @Test(description = "Simulate uniform random jitter bounded between 200ms and 600ms")
    public void testUniformRandomJitter() {
        // Uniform distribution: delay is evenly distributed between lower and upper bounds
        stubFor(get(urlEqualTo("/v1/courses/catalog"))
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withUniformRandomDelay(200, 600)
                        .withBody("{\"catalogStatus\": \"ONLINE\"}")));

        long start = System.currentTimeMillis();

        given()
            .spec(mockSpec)
        .when()
            .get("/v1/courses/catalog")
        .then()
            .statusCode(200)
            .time(greaterThanOrEqualTo(180L))
            .time(lessThan(1000L));

        long duration = System.currentTimeMillis() - start;
        System.out.printf("[Uniform Jitter] Round-trip latency: %d ms (Expected: 200-600ms)%n", duration);
    }
}
Jitter Distribution Telemetry: [LogNormal Sample 1] Round-trip latency: 312 ms [LogNormal Sample 2] Round-trip latency: 284 ms [LogNormal Sample 3] Round-trip latency: 688 ms (Long-tail latency spike captured) [Uniform Jitter] Round-trip latency: 442 ms (Expected: 200-600ms) Validates that client thread pools handle variable network latency without thread starvation.
Real-Time Example 6: Slow Body Delivery via Chunked Dribble Delay
Testing slow-read and streaming client handlers. Configures withChunkedDribbleDelay(numberOfChunks, totalDuration) in WireMock to deliver response payload bytes in tiny, metered chunks across a defined duration.
Java (Chunked Dribble Delay Slow-Stream Simulation)
package com.nikita.restassured.wiremock.faults;

import com.nikita.restassured.wiremock.WireMockBaseTest;
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;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;

public class ChunkedDribbleDelayTest extends WireMockBaseTest {

    @Test(description = "Verify client handles slowly-trickling chunked responses using ChunkedDribbleDelay")
    public void testSlowChunkedDribble() {
        // Dribbles the response payload in 5 distinct chunks over 1500ms total duration
        stubFor(get(urlEqualTo("/v1/media/slow-payload"))
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withChunkedDribbleDelay(5, 1500) // 5 chunks over 1.5 seconds
                        .withBody("{\"streamStatus\": \"FULLY_DELIVERED\", \"totalBytes\": 1024}")));

        long start = System.currentTimeMillis();

        given()
            .spec(mockSpec)
        .when()
            .get("/v1/media/slow-payload")
        .then()
            .statusCode(200)
            .body("streamStatus", equalTo("FULLY_DELIVERED"))
            .time(greaterThanOrEqualTo(1400L)); // Must take at least 1.4s to assemble

        long duration = System.currentTimeMillis() - start;
        System.out.printf("[βœ”] Dribbled payload assembled successfully in %d ms (Dribble total: 1500ms)%n", duration);
    }
}
Chunked Dribble Output: GET http://localhost:52419/v1/media/slow-payload -> Streaming in 5 chunks over 1500ms... Chunk 1: 205 bytes [T+300ms] Chunk 2: 205 bytes [T+600ms] Chunk 3: 205 bytes [T+900ms] Chunk 4: 205 bytes [T+1200ms] Chunk 5: 204 bytes [T+1500ms] [βœ”] Dribbled payload assembled successfully in 1538 ms (Dribble total: 1500ms) PASSED: testSlowChunkedDribble
Real-Time Example 7: Client Circuit Breaker Testing: From CLOSED to OPEN to HALF-OPEN
Verifying circuit breaker resilience (e.g. Resilience4j). Combines WireMock faults, status 503 errors, and state transitions to confirm that repeated downstream failures trip the circuit breaker open, blocking calls before re-closing.
Java (Testing Circuit Breaker State Transitions with WireMock)
package com.nikita.restassured.wiremock.faults;

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.http.Fault;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import org.testng.Assert;
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;

public class CircuitBreakerResilienceTest {

    private WireMockServer circuitServer;
    private RequestSpecification circuitSpec;

    @BeforeClass
    public void setup() {
        circuitServer = new WireMockServer(WireMockConfiguration.options().dynamicPort());
        circuitServer.start();

        circuitSpec = new RequestSpecBuilder()
                .setBaseUri(circuitServer.baseUrl())
                .build();

        // SCENARIO: Trip circuit breaker with failures, then recover
        // Call 1: Server fails with Fault.EMPTY_RESPONSE -> Transitions to FAILURE_1
        circuitServer.stubFor(get(urlEqualTo("/v1/service/payment"))
                .inScenario("CircuitBreakerScenario")
                .whenScenarioStateIs(Scenario.STARTED)
                .willSetStateTo("FAILURE_1")
                .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE)));

        // Call 2: Server fails again with 503 Unavailable -> Transitions to CIRCUIT_OPEN
        circuitServer.stubFor(get(urlEqualTo("/v1/service/payment"))
                .inScenario("CircuitBreakerScenario")
                .whenScenarioStateIs("FAILURE_1")
                .willSetStateTo("CIRCUIT_OPEN")
                .willReturn(aResponse().withStatus(503).withBody("Service Unavailable")));

        // Call 3: Service recovers and returns 200 OK
        circuitServer.stubFor(get(urlEqualTo("/v1/service/payment"))
                .inScenario("CircuitBreakerScenario")
                .whenScenarioStateIs("CIRCUIT_OPEN")
                .willReturn(aResponse().withStatus(200).withBody("{\"status\": \"RECOVERED\"}")));
    }

    @Test(description = "Verify sequential state transitions through failure to recovery")
    public void testCircuitBreakerLifecycle() {
        // Invocations:
        // Attempt 1: Expect socket failure
        try {
            given().spec(circuitSpec).get("/v1/service/payment");
            Assert.fail("Attempt 1 should fail with dropped socket");
        } catch (Exception expected) {
            System.out.println("[*] Attempt 1 failed (Fault injected) -> Circuit tracking failure count: 1");
        }

        // Attempt 2: Expect 503 response
        int attempt2Status = given().spec(circuitSpec).get("/v1/service/payment").getStatusCode();
        Assert.assertEquals(attempt2Status, 503);
        System.out.println("[*] Attempt 2 returned HTTP 503 -> Circuit breaker tripped to OPEN");

        // Attempt 3: Service recovered, returns 200 OK
        int attempt3Status = given().spec(circuitSpec).get("/v1/service/payment").getStatusCode();
        Assert.assertEquals(attempt3Status, 200);
        System.out.println("[βœ”] Attempt 3 returned HTTP 200 -> Service recovered successfully");
    }

    @AfterClass(alwaysRun = true)
    public void teardown() {
        if (circuitServer != null) {
            circuitServer.stop();
        }
    }
}
Circuit Breaker Telemetry: [*] Attempt 1 failed (Fault injected) -> Circuit tracking failure count: 1 [*] Attempt 2 returned HTTP 503 -> Circuit breaker tripped to OPEN [*] Attempt 3 returned HTTP 200 -> Service recovered successfully PASSED: testCircuitBreakerLifecycle
Real-Time Example 8: Debugging Hanging Tests & Unbounded Delay Triage
Troubleshooting common latency testing pitfalls: diagnosing hanging CI builds caused by unbounded delays, configuring safety caps on TestNG @Test(timeOut = ...), and verifying thread release on interrupted sockets.
Java (Triage: TestNG Execution Timeouts & Hanging Delay Guards)
package com.nikita.restassured.wiremock.faults;

import com.nikita.restassured.wiremock.WireMockBaseTest;
import io.restassured.config.HttpClientConfig;
import io.restassured.config.RestAssuredConfig;
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 DelayTriageTest extends WireMockBaseTest {

    // ==========================================================================
    // PITFALL: UNBOUNDED DELAYS HANGING CI/CD BUILDS
    // When testing with withFixedDelay(30000) (30 seconds), if the client does not
    // have an explicit socket timeout, the worker thread hangs indefinitely,
    // causing CI pipeline jobs to time out after 60 minutes!
    //
    // DEFENSIVE MEASURE 1: Always set @Test(timeOut = 5000) in TestNG as a safety net!
    // DEFENSIVE MEASURE 2: Always configure http.socket.timeout on RestAssuredConfig!
    // ==========================================================================

    @Test(timeOut = 4000, description = "TestNG safety timeout ensures test aborts if client hangs on delay")
    public void testSafeExecutionWithTimeoutGuard() {
        // WireMock set to delay for 2000ms
        stubFor(get(urlEqualTo("/v1/triage/bounded-delay"))
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withFixedDelay(2000)
                        .withBody("{\"triage\": \"BOUNDED_OK\"}")));

        RestAssuredConfig safeConfig = RestAssuredConfig.config()
                .httpClient(HttpClientConfig.httpClientConfig()
                        .setParam("http.socket.timeout", 3000)
                        .setParam("http.connection.timeout", 2000));

        long start = System.currentTimeMillis();

        given()
            .spec(mockSpec)
            .config(safeConfig)
        .when()
            .get("/v1/triage/bounded-delay")
        .then()
            .statusCode(200);

        long duration = System.currentTimeMillis() - start;
        System.out.printf("[βœ”] Bounded delay test completed in %d ms (Well within 4000ms TestNG guard)%n", duration);
        Assert.assertTrue(duration >= 1900 && duration < 3500);
    }
}
Triage Diagnostic Breakdown: - Problem: Tests without timeout guards hang indefinitely when server delays are misconfigured. - Guard 1: @Test(timeOut = 4000) ensures TestNG interrupts the thread if the test exceeds 4 seconds. - Guard 2: http.socket.timeout = 3000 ensures Apache HttpClient aborts the socket before the test-level timeout. Result: Eliminates hanging test runners in Jenkins, GitLab CI, and GitHub Actions.
Real-Time Example 9: WireMock Faults & Delays Reference Matrix
A comprehensive reference summary pairing WireMock fault types, latency distributions, client exceptions, and operational best practices for resilience testing.
Fault Injection & Latency Specification Reference Matrix
WIREMOCK FAULT INJECTION & LATENCY SPECIFICATION MATRIX:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ FAULT / DELAY CONSTRUCT β”‚ DSL SYNTAX EXAMPLE           β”‚ CLIENT EXCEPTION β”‚ PRIMARY RESILIENCE OBJECTIVE  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Empty Response          β”‚ withFault(Fault.EMPTY_RESP)  β”‚ NoHttpResponseEx β”‚ Simulates socket drop with 0B β”‚
β”‚ Random Data & Close     β”‚ withFault(Fault.RANDOM_DATA) β”‚ ProtocolExceptionβ”‚ Tests malformed packet guard  β”‚
β”‚ Malformed Chunk Frame   β”‚ withFault(Fault.MALFORMED..) β”‚ MalformedChunkEx β”‚ Tests broken chunked transfersβ”‚
β”‚ Reset By Peer           β”‚ withFault(Fault.PEER_RESET)  β”‚ SocketException  β”‚ Simulates TCP RST packet dropsβ”‚
β”‚ Fixed Latency Delay     β”‚ withFixedDelay(2000)         β”‚ SocketTimeoutEx  β”‚ Validates client SLA timeouts β”‚
β”‚ LogNormal Jitter        β”‚ withLogNormalRandomDelay(m,s)β”‚ N/A (Statistical)β”‚ Models realistic long-tail lagβ”‚
β”‚ Uniform Jitter          β”‚ withUniformRandomDelay(min,m)β”‚ N/A (Bounded)    β”‚ Simulates latency variance    β”‚
β”‚ Chunked Dribble Delay   β”‚ withChunkedDribbleDelay(c,ms)β”‚ Slow stream read β”‚ Tests streaming read timeouts β”‚
β”‚ Global Delay Setting    β”‚ WireMock.setGlobalDelay(ms)  β”‚ All endpoints    β”‚ Adds baseline lag globally    β”‚
β”‚ TestNG Timeout Guard    β”‚ @Test(timeOut = 5000)        β”‚ TestTimeoutEx    β”‚ Prevents hung CI test workers β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ TOP 5 FAULT INJECTION & LATENCY BEST PRACTICES:                                                           β”‚
β”‚ 1. Always set @Test(timeOut = ...) guards: Prevent hanging CI builds during latency testing.              β”‚
β”‚ 2. Test both connection and socket timeouts: Differentiate between connect lag and read delays.           β”‚
β”‚ 3. Use LogNormal distributions for realistic lag: Capture 99th-percentile spikes beyond static delays.    β”‚
β”‚ 4. Verify circuit breaker state transitions: Test OPEN, HALF-OPEN, and CLOSED states with stubs.          β”‚
β”‚ 5. Validate client fallback logic on Fault.EMPTY_RESPONSE: Confirm graceful degradation on drops.         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Fault injection and latency simulation transform functional test suites into true resilience engineering platforms. By testing TCP socket drops, protocol corruptions, chunked dribble delays, and statistical jitter against REST Assured clients, you verify that your application handles production network instability gracefully before outages impact end users.