๐ฎ Simulating Unavailable, Costly, and Flaky Downstream Dependencies
In microservice and cloud-native architectures, executing comprehensive integration tests against real external dependencies (e.g., third-party payment gateways like Razorpay/Stripe, SMS brokers, legacy core-banking mainframes, or cloud IAM providers) introduces critical blockers. Real third-party endpoints incur transaction costs, enforce strict rate limits, cannot trigger destructive error paths on demand, and suffer from network latency that destabilizes automated pipelines. Service Virtualization emulates the behavior, protocols, and stateful transactions of dependent systems at the network transport layer. Using enterprise tools like WireMock and MockServer, engineering teams capture and replay production traffic, stub HTTP/HTTPS/gRPC interfaces, inject network faults (socket drops, connection timeouts, randomized packet corruptions), and simulate stateful multi-step business journeys within isolated test environments.
EMULATION TOPOGRAPHY & BOUNDARY DEFINITIONS:
โโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ DIMENSION โ UNIT MOCK (Mockito/Magic)โ API STUB (Static Mock) โ SERVICE VIRTUALIZATION (WireMock/Server) โ
โโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Execution Layer โ In-memory JVM/Python RAM โ Local HTTP server โ Full Network Socket Server (TCP/TLS) โ
โ Protocol Realism โ None (Direct code call) โ Basic HTTP 200/400 JSON โ HTTP/1.1, HTTP/2, gRPC, HTTPS, WebSocketsโ
โ Statefulness โ Ephemeral per test methodโ Stateless request/reply โ Stateful Finite State Machines (FSM) โ
โ Fault Simulation โ Throws Java Exception โ Static error status code โ Network latency, socket drops, bad chunksโ
โ System Under Test โ Individual Class/Method โ Individual Microservice โ Entire Distributed Ecosystem / Subsystem โ
โโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
VIRTUALIZATION DEPLOYMENT ARCHITECTURE:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ SYSTEM UNDER TEST (SUT) โ โ VIRTUALIZED DEPENDENCY (WireMock) โ
โ โ HTTP / HTTPS Wire โ โ
โ [ Core Enrollment Microservice ] โ โโโโโโโโโโโโโโโโโโโบ โ [ WireMock Server :8089 ] โ
โ โโโ StudentController โ POST /v1/payments โ โโโ Request Matchers (URL, Body) โ
โ โโโ PaymentGatewayClient โ โโโโโโโโโโโโโโโโโโโ โ โโโ Stateful Scenario Engine โ
โ (Configured to point to โ {"status":"OK"} โ โโโ Chaos Fault Injector (Delay) โ
โ localhost:8089) โ โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
package com.nikitainfotech.api.virtualization;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
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 WireMockJUnit5IntegrationTest {
// Register WireMock with dynamic port allocation to prevent port conflict during parallel CI runs
@RegisterExtension
static WireMockExtension wiremock = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
.build();
@Test
public void testStudentFeeVerificationStub() {
// 1. Arrange: Define stub mapping for payment verification endpoint
wiremock.stubFor(post(urlEqualTo("/api/v1/payments/verify"))
.withHeader("Authorization", matching("Bearer .+"))
.withRequestBody(matchingJsonPath("$.studentId", matching("^STU-[0-9]{5}$")))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{"
+ "\"transactionId\":\"TXN-99120481\","
+ "\"feeSettled\":true,"
+ "\"currency\":\"INR\","
+ "\"amount\":14999.00"
+ "}")));
// 2. Act & Assert: RestAssured queries the virtualized service endpoint
RestAssured.given()
.baseUri(wiremock.baseUrl())
.contentType(ContentType.JSON)
.header("Authorization", "Bearer mock-active-jwt-token")
.body("{\"studentId\":\"STU-88219\",\"courseCode\":\"API-PRO-101\"}")
.when()
.post("/api/v1/payments/verify")
.then()
.statusCode(200)
.body("transactionId", equalTo("TXN-99120481"))
.body("feeSettled", equalTo(true))
.body("currency", equalTo("INR"));
// 3. Verify: Assert WireMock received exactly 1 invocation matching the criteria
wiremock.verify(1, postRequestedFor(urlEqualTo("/api/v1/payments/verify"))
.withHeader("Authorization", containing("Bearer")));
}
}
mappings/ and __files/ directory hierarchy.
{
"request": {
"method": "POST",
"urlPattern": "/api/v1/students/([0-9]+)/enroll",
"headers": {
"Content-Type": {
"equalTo": "application/json"
},
"X-Idempotency-Key": {
"matches": "^IDEM-[a-f0-9-]{36}$"
}
},
"bodyPatterns": [
{
"matchesJsonPath": "$.courses[?(@.credits >= 3)]"
}
]
},
"response": {
"status": 201,
"headers": {
"Content-Type": "application/json; charset=utf-8",
"Location": "/api/v1/students/101/enrollments/ENR-99214"
},
"jsonBody": {
"enrollmentId": "ENR-99214",
"status": "CONFIRMED",
"enrolledAt": "2026-11-01T12:00:00Z",
"allocatedCredits": 4
},
"fixedDelayMilliseconds": 150
}
}
{
"request": {
"method": "POST",
"url": "/api/v1/certificates/issue"
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"transformers": ["response-template"],
"jsonBody": {
"certificateNumber": "CERT-{{randomValue type='UUID'}}",
"recipientName": "{{jsonPath request.body '$.studentName'}}",
"recipientEmail": "{{jsonPath request.body '$.email'}}",
"courseCompleted": "{{jsonPath request.body '$.courseCode'}}",
"issuedTimestamp": "{{now format='yyyy-MM-dd HH:mm:ss'}}",
"verificationUrl": "https://verify.nikita-infotech.com/audit/{{jsonPath request.body '$.studentId'}}",
"clientEchoIp": "{{request.clientIp}}"
}
}
}
503 Service Unavailable on the first two attempts, then succeeds with 200 OK on the third retry.
package com.nikitainfotech.api.virtualization;
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 com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED;
@WireMockTest(httpPort = 8089)
public class PaymentRetryScenarioTest {
private static final String SCENARIO_NAME = "Resilient_Payment_Retry_Workflow";
@Test
public void testClientRecoversFromTransientFailures() {
// STATE 1: Initial call arrives in STARTED state -> Returns 503 & transitions to ATTEMPT_2
stubFor(post("/api/v1/payments/charge")
.inScenario(SCENARIO_NAME)
.whenScenarioStateIs(STARTED)
.willSetStateTo("ATTEMPT_2")
.willReturn(aResponse()
.withStatus(503)
.withHeader("Retry-After", "1")
.withBody("{\"error\":\"TRANSIENT_GATEWAY_TIMEOUT\"}")));
// STATE 2: Second call arrives in ATTEMPT_2 state -> Returns 503 & transitions to ATTEMPT_3
stubFor(post("/api/v1/payments/charge")
.inScenario(SCENARIO_NAME)
.whenScenarioStateIs("ATTEMPT_2")
.willSetStateTo("ATTEMPT_3")
.willReturn(aResponse()
.withStatus(503)
.withBody("{\"error\":\"PAYMENT_ENGINE_OVERLOADED\"}")));
// STATE 3: Third call arrives in ATTEMPT_3 state -> Returns 200 OK and settles charge
stubFor(post("/api/v1/payments/charge")
.inScenario(SCENARIO_NAME)
.whenScenarioStateIs("ATTEMPT_3")
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"status\":\"SETTLED\",\"transactionId\":\"TXN-RETRY-SUCCESS\"}")));
// Execution Step 1: Call 1 fails with 503
RestAssured.given().baseUri("http://localhost:8089")
.post("/api/v1/payments/charge").then().statusCode(503);
// Execution Step 2: Call 2 fails with 503
RestAssured.given().baseUri("http://localhost:8089")
.post("/api/v1/payments/charge").then().statusCode(503);
// Execution Step 3: Call 3 succeeds with 200 OK
RestAssured.given().baseUri("http://localhost:8089")
.post("/api/v1/payments/charge").then().statusCode(200);
// Verify that exactly 3 calls were executed during the scenario lifecycle
verify(3, postRequestedFor(urlEqualTo("/api/v1/payments/charge")));
}
}
package com.nikitainfotech.api.virtualization;
import com.github.tomakehurst.wiremock.http.Fault;
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.junit.jupiter.api.Assertions.assertThrows;
@WireMockTest(httpPort = 8089)
public class WireMockFaultInjectionTest {
@Test
public void testSocketDropFaultInjection() {
// Injects CONNECTION_RESET_BY_PEER: Closes TCP socket abruptly mid-transmission
stubFor(get("/api/v1/unstable-resource")
.willReturn(aResponse()
.withFault(Fault.CONNECTION_RESET_BY_PEER)));
// Client must catch socket disconnection exception and handle fallback gracefully
assertThrows(Exception.class, () -> {
RestAssured.get("http://localhost:8089/api/v1/unstable-resource");
});
}
@Test
public void testGarbagePayloadInjection() {
// Injects RANDOM_DATA_THEN_CLOSE: Transmits random junk bytes, breaking JSON parsers
stubFor(get("/api/v1/corrupt-data")
.willReturn(aResponse()
.withFault(Fault.RANDOM_DATA_THEN_CLOSE)));
assertThrows(Exception.class, () -> {
RestAssured.get("http://localhost:8089/api/v1/corrupt-data");
});
}
@Test
public void testSevereLatencyTimeoutSimulation() {
// Injects 8000ms delay to verify client SocketTimeoutException triggers
stubFor(get("/api/v1/slow-service")
.willReturn(aResponse()
.withStatus(200)
.withFixedDelay(8000)
.withBody("{\"status\":\"TOO_LATE\"}")));
RestAssured.given()
.config(RestAssured.config().httpClient(
io.restassured.config.HttpClientConfig.httpClientConfig()
.setParam("http.socket.timeout", 2000) // 2.0s client timeout
))
.when()
.get("http://localhost:8089/api/v1/slow-service"); // Fails fast with SocketTimeoutException
}
}
# 1. LAUNCH WIREMOCK IN REVERSE PROXY RECORDING MODE VIA CLI:
java -jar wiremock-standalone-3.4.2.jar \
--port 8089 \
--proxy-all="https://api.nikita-infotech.com" \
--record-mappings \
--verbose
# 2. DISPATCH CLIENT REQUEST THROUGH THE WIREMOCK PROXY:
curl -X GET "http://localhost:8089/v1/students/STU-88219" \
-H "Authorization: Bearer mock-jwt-token"
# 3. WHAT WIREMOCK DOES AUTOMATICALLY:
# - Forwards request to real upstream server: https://api.nikita-infotech.com
# - Captures HTTP status, headers, and response payload bytes
# - Writes generated stub to: mappings/v1_students_stu-88219.json
# - Saves body payload snapshot to: __files/body-v1-students-stu-88219.json
# 4. SWITCH TO REPLAY MODE (TERMINATE UPSTREAM ACCESS):
# Re-run WireMock without --proxy-all; it now serves captured traffic completely offline!
java -jar wiremock-standalone-3.4.2.jar --port 8089
mockserver-client library, declaring path patterns, regex matches, and verifying interaction counts.
import pytest
import requests
from mockserver import MockServerClient, request, response, times
MOCKSERVER_HOST = "localhost"
MOCKSERVER_PORT = 1080
BASE_MOCK_URL = f"http://{MOCKSERVER_HOST}:{MOCKSERVER_PORT}"
class TestMockServerVirtualization:
@pytest.fixture(autouse=True)
def setup_mockserver(self):
self.client = MockServerClient(f"http://{MOCKSERVER_HOST}:{MOCKSERVER_PORT}")
self.client.reset() # Clear all active expectations before each test
yield
self.client.reset()
def test_mockserver_payment_expectation(self):
# 1. Define expectations on MockServer
self.client.expect(
request(
method="POST",
path="/api/v1/subscriptions/activate",
headers={"Content-Type": ["application/json"]},
body={"studentId": "STU-88219", "tier": "ENTERPRISE"}
),
response(
status_code=200,
headers={"Content-Type": ["application/json"]},
body={"subscriptionId": "SUB-9912048", "active": True}
),
times(1) # Expect exactly 1 interaction
)
# 2. Application client invokes the virtualized endpoint
res = requests.post(
f"{BASE_MOCK_URL}/api/v1/subscriptions/activate",
json={"studentId": "STU-88219", "tier": "ENTERPRISE"},
headers={"Content-Type": "application/json"}
)
# 3. Assert Response received from MockServer
assert res.status_code == 200
data = res.json()
assert data["subscriptionId"] == "SUB-9912048"
assert data["active"] is True
# 4. Verify request was received by MockServer
self.client.verify(
request(method="POST", path="/api/v1/subscriptions/activate"),
count=1
)
package com.nikitainfotech.api.virtualization;
import io.restassured.RestAssured;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.MountableFile;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@Testcontainers
public class WireMockTestcontainersTest {
// Spins up official WireMock container mounting local mapping configurations
@Container
private static final GenericContainer<?> wiremockContainer =
new GenericContainer<>("wiremock/wiremock:3.4.2")
.withExposedPorts(8080)
.withCopyFileToContainer(
MountableFile.forClasspathResource("wiremock/mappings"),
"/home/wiremock/mappings"
);
private static String wiremockBaseUrl;
@BeforeAll
public static void setup() {
wiremockContainer.start();
Integer mappedPort = wiremockContainer.getMappedPort(8080);
wiremockBaseUrl = "http://" + wiremockContainer.getHost() + ":" + mappedPort;
System.out.println("[+] Testcontainers WireMock running at: " + wiremockBaseUrl);
}
@Test
public void testContainerizedVirtualService() {
given()
.baseUri(wiremockBaseUrl)
.when()
.get("/api/v1/courses/catalog")
.then()
.statusCode(200)
.body("track", equalTo("API-PRO-101"));
}
@AfterAll
public static void tearDown() {
wiremockContainer.stop();
}
}
SERVICE VIRTUALIZATION & FAULT INJECTION REFERENCE MATRIX:
โโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CAPABILITY / FEATURE โ TOOL IMPLEMENTATION โ PRIMARY PURPOSE & TESTING ADVANTAGE โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Dynamic Port Binding โ dynamicPort() โ Prevents port binding collisions during parallel CIโ
โ Response Templating โ Handlebars {{jsonPath ..}} โ Echoes dynamic request parameters in responses โ
โ Scenario State Machine โ inScenario().whenStateIs(..) โ Simulates stateful workflows (retry recovery) โ
โ Network Fault Injection โ withFault(Fault.CONNECTION..)โ Injects socket drops, packet resets, junk bytes โ
โ Fixed / Chunked Delay โ withFixedDelay(milliseconds) โ Simulates high-latency SLAs and timeout limits โ
โ Record & Playback โ --proxy-all --record-mappingsโ Captures live production traffic into stubs โ
โ Verification Assertions โ wiremock.verify(count, req) โ Confirms exact count of wire requests dispatched โ
โ Testcontainers Support โ GenericContainer(wiremock) โ Containerized zero-dependency CI test execution โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ TOP 5 SERVICE VIRTUALIZATION BEST PRACTICES: โ
โ 1. Never hardcode ports: Use dynamicPort() to ensure parallel test runs execute cleanly without conflicts. โ
โ 2. Test error paths first: Virtualize 500, 502, 503, and 504 errors that real APIs cannot trigger on demand.โ
โ 3. Inject chaos faults: Validate socket disconnections and timeouts to test client resilience. โ
โ 4. Keep stubs isolated: Reset stubs between tests (resetAll() / clean expectations) to prevent state leaks. โ
โ 5. Store stubs in Git: Commit JSON mapping definitions alongside test code for reproducible CI runs. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ