π Evolving Beyond Stateless Request-Response Stubs
Standard API mocks are traditionally stateless: regardless of how many times a client calls GET /api/v1/orders/101, the server returns the exact same hardcoded JSON payload. While suitable for basic unit isolation, this stateless model fails when validating real-world enterprise architectures that depend on state transitionsβsuch as long-running asynchronous batch jobs, payment gateway polling loops (moving from INITIATED to PENDING to SETTLED), checkout cart item accumulations, or circuit breaker tripped states. Stateful Mocking models the downstream service as a Finite State Machine (FSM). By defining states, prerequisite state gates (whenScenarioStateIs), and state transitions (willSetStateTo) in tools like WireMock and MockServer, quality engineering teams can simulate intricate, multi-step asynchronous business workflows deterministically within local automated test runs.
FINITE STATE MACHINE (FSM) TOPOGRAPHY IN VIRTUAL SERVICES:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FORMAL FSM TUPLE: M = (S, s0, Ξ£, Ξ΄, F) β
β - S : Set of all possible states (e.g. Started, Pending, Processing, Completed, Failed) β
β - s0 : Default initial state (Scenario.STARTED in WireMock) β
β - Ξ£ : Input alphabet (Incoming HTTP requests: GET, POST, PUT, DELETE + payload matching) β
β - Ξ΄ : Transition function: Ξ΄(Current State, Incoming HTTP Call) βββΊ (Next State, Response) β
β - F : Set of terminal states (COMPLETED / CANCELLED) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
TYPICAL ASYNCHRONOUS POLLING STATE MACHINE WORKFLOW:
βββββββββββββββββββββββββββ HTTP GET βββββββββββββββββββββββββββ
β Scenario.STARTED β βββββββββββββββββββββββββββββββββββββΊ β Poll 1: Returns 202 β
β (Job just submitted) β β status: "QUEUED" β
βββββββββββββββββββββββββββ βββββββββββββββββββββββββββ
β β
β (willSetStateTo: "IN_PROGRESS") β
βΌ βΌ
βββββββββββββββββββββββββββ HTTP GET βββββββββββββββββββββββββββ
β IN_PROGRESS β βββββββββββββββββββββββββββββββββββββΊ β Poll 2: Returns 200 β
β (Worker processing) β β status: "PROCESSING" β
βββββββββββββββββββββββββββ βββββββββββββββββββββββββββ
β β
β (willSetStateTo: "JOB_DONE") β
βΌ βΌ
βββββββββββββββββββββββββββ HTTP GET βββββββββββββββββββββββββββ
β JOB_DONE β βββββββββββββββββββββββββββββββββββββΊ β Poll 3+: Returns 200 β
β (Terminal execution) β β status: "COMPLETED" β
βββββββββββββββββββββββββββ βββββββββββββββββββββββββββ
202 Accepted with progress percentages over multiple polling requests before transitioning to 200 OK with the final download URI.
package com.nikitainfotech.api.scenarios;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED;
import static org.hamcrest.Matchers.equalTo;
@WireMockTest(httpPort = 8089)
public class AsyncReportPollingScenarioTest {
private static final String SCENARIO = "Async_Report_Generation";
@Test
public void testClientPollsUntilReportGenerationCompletes() throws InterruptedException {
// STATE 1: Initial call (STARTED) -> Returns 202 Accepted, progress 15% -> Next: PROCESSING
stubFor(get("/api/v1/reports/RPT-9912/status")
.inScenario(SCENARIO)
.whenScenarioStateIs(STARTED)
.willSetStateTo("PROCESSING")
.willReturn(aResponse()
.withStatus(202)
.withHeader("Content-Type", "application/json")
.withBody("{\"jobId\":\"RPT-9912\",\"status\":\"QUEUED\",\"progress\":15}")));
// STATE 2: In-Progress call -> Returns 200 OK, progress 75% -> Next: READY
stubFor(get("/api/v1/reports/RPT-9912/status")
.inScenario(SCENARIO)
.whenScenarioStateIs("PROCESSING")
.willSetStateTo("READY")
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"jobId\":\"RPT-9912\",\"status\":\"BUILDING\",\"progress\":75}")));
// STATE 3: Ready state -> Returns 200 OK, progress 100% and download URL (Terminal State)
stubFor(get("/api/v1/reports/RPT-9912/status")
.inScenario(SCENARIO)
.whenScenarioStateIs("READY")
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"jobId\":\"RPT-9912\",\"status\":\"COMPLETED\",\"progress\":100,\"downloadUrl\":\"https://cdn.nikita-infotech.com/reports/rpt-9912.pdf\"}")));
// CLIENT POLLING LOOP EXECUTION:
String status = "";
int attempts = 0;
String finalDownloadUrl = "";
while (!"COMPLETED".equals(status) && attempts < 5) {
attempts++;
Response res = RestAssured.get("http://localhost:8089/api/v1/reports/RPT-9912/status");
status = res.jsonPath().getString("status");
int progress = res.jsonPath().getInt("progress");
System.out.println(String.format("Polling Attempt #%d -> Status: %s (Progress: %d%%)", attempts, status, progress));
if ("COMPLETED".equals(status)) {
finalDownloadUrl = res.jsonPath().getString("downloadUrl");
break;
}
Thread.sleep(100); // Polling interval
}
// Assertions
org.junit.jupiter.api.Assertions.assertEquals(3, attempts, "Expected exactly 3 polling cycles!");
org.junit.jupiter.api.Assertions.assertEquals("https://cdn.nikita-infotech.com/reports/rpt-9912.pdf", finalDownloadUrl);
}
}
mappings/ folder for standalone WireMock or Docker instances without writing Java code.
[
{
"scenarioName": "Subscription_Cancellation_Flow",
"requiredScenarioState": "Started",
"newScenarioState": "CANCELLED_PENDING",
"request": {
"method": "POST",
"url": "/api/v1/subscriptions/SUB-1001/cancel",
"bodyPatterns": [
{ "matchesJsonPath": "$.reason" }
]
},
"response": {
"status": 202,
"headers": { "Content-Type": "application/json" },
"jsonBody": {
"subscriptionId": "SUB-1001",
"status": "CANCELLATION_SCHEDULED",
"activeUntil": "2026-11-30T23:59:59Z"
}
}
},
{
"scenarioName": "Subscription_Cancellation_Flow",
"requiredScenarioState": "CANCELLED_PENDING",
"request": {
"method": "GET",
"url": "/api/v1/subscriptions/SUB-1001"
},
"response": {
"status": 200,
"headers": { "Content-Type": "application/json" },
"jsonBody": {
"subscriptionId": "SUB-1001",
"plan": "ENTERPRISE_ANNUAL",
"status": "TERMINATING",
"renewAuto": false
}
}
}
]
package com.nikitainfotech.api.scenarios;
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 CircuitBreakerStatefulSimulationTest {
private static final String SCENARIO = "Payment_Gateway_Circuit_Breaker";
@Test
public void testSimulateOutageAndRecoveryCycle() {
// CALL 1: Healthy initial call -> 200 OK -> Transitions to FAIL_BURST_1
stubFor(get("/api/v1/gateway/health")
.inScenario(SCENARIO)
.whenScenarioStateIs(STARTED)
.willSetStateTo("FAIL_BURST_1")
.willReturn(aResponse().withStatus(200).withBody("{\"state\":\"HEALTHY\"}")));
// CALL 2: Downstream failure 1 -> 500 Internal Error -> Transitions to FAIL_BURST_2
stubFor(get("/api/v1/gateway/health")
.inScenario(SCENARIO)
.whenScenarioStateIs("FAIL_BURST_1")
.willSetStateTo("FAIL_BURST_2")
.willReturn(aResponse().withStatus(500).withBody("{\"error\":\"INTERNAL_FAULT\"}")));
// CALL 3: Downstream failure 2 (Threshold breached) -> 503 -> Transitions to RECOVERED
stubFor(get("/api/v1/gateway/health")
.inScenario(SCENARIO)
.whenScenarioStateIs("FAIL_BURST_2")
.willSetStateTo("RECOVERED")
.willReturn(aResponse().withStatus(503).withBody("{\"error\":\"CIRCUIT_BREAKER_TRIPPED\"}")));
// CALL 4: Recovery call -> Service back online -> 200 OK
stubFor(get("/api/v1/gateway/health")
.inScenario(SCENARIO)
.whenScenarioStateIs("RECOVERED")
.willReturn(aResponse().withStatus(200).withBody("{\"state\":\"RESTORED\"}")));
// Execute sequential transitions
RestAssured.get("http://localhost:8089/api/v1/gateway/health").then().statusCode(200);
RestAssured.get("http://localhost:8089/api/v1/gateway/health").then().statusCode(500);
RestAssured.get("http://localhost:8089/api/v1/gateway/health").then().statusCode(503);
RestAssured.get("http://localhost:8089/api/v1/gateway/health").then().statusCode(200);
verify(4, getRequestedFor(urlEqualTo("/api/v1/gateway/health")));
}
}
GET), adding an item (POST), verifying the populated cart (GET), and checking out (DELETE).
package com.nikitainfotech.api.scenarios;
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;
import static org.hamcrest.Matchers.*;
@WireMockTest(httpPort = 8089)
public class ShoppingCartWorkflowScenarioTest {
private static final String CART_SCENARIO = "Student_Course_Cart_Workflow";
@Test
public void testFullCartLifecycleAcrossMultipleEndpoints() {
// 1. GET /cart while in STARTED state -> Cart is empty
stubFor(get("/api/v1/cart")
.inScenario(CART_SCENARIO)
.whenScenarioStateIs(STARTED)
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"itemCount\":0,\"items\":[],\"totalAmount\":0.00}")));
// 2. POST /cart/items -> Adds course and transitions state to "CART_POPULATED"
stubFor(post("/api/v1/cart/items")
.inScenario(CART_SCENARIO)
.whenScenarioStateIs(STARTED)
.willSetStateTo("CART_POPULATED")
.willReturn(aResponse()
.withStatus(201)
.withHeader("Content-Type", "application/json")
.withBody("{\"message\":\"Course added\",\"courseCode\":\"API-PRO-101\"}")));
// 3. GET /cart while in "CART_POPULATED" state -> Returns populated cart
stubFor(get("/api/v1/cart")
.inScenario(CART_SCENARIO)
.whenScenarioStateIs("CART_POPULATED")
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"itemCount\":1,\"items\":[{\"code\":\"API-PRO-101\",\"price\":14999.00}],\"totalAmount\":14999.00}")));
// 4. POST /cart/checkout while in "CART_POPULATED" state -> Transitions to "CHECKOUT_COMPLETE"
stubFor(post("/api/v1/cart/checkout")
.inScenario(CART_SCENARIO)
.whenScenarioStateIs("CART_POPULATED")
.willSetStateTo("CHECKOUT_COMPLETE")
.willReturn(aResponse()
.withStatus(200)
.withBody("{\"orderId\":\"ORD-88219\",\"status\":\"PAID\"}")));
// 5. GET /cart after checkout -> Cart is empty again
stubFor(get("/api/v1/cart")
.inScenario(CART_SCENARIO)
.whenScenarioStateIs("CHECKOUT_COMPLETE")
.willReturn(aResponse()
.withStatus(200)
.withBody("{\"itemCount\":0,\"items\":[],\"totalAmount\":0.00}")));
// CLIENT EXECUTION SEQUENCE:
String baseUrl = "http://localhost:8089/api/v1/cart";
// Step 1: Initial empty cart check
RestAssured.get(baseUrl).then().statusCode(200).body("itemCount", equalTo(0));
// Step 2: Add course to cart
RestAssured.post(baseUrl + "/items").then().statusCode(201);
// Step 3: Verify cart now contains 1 item
RestAssured.get(baseUrl).then().statusCode(200).body("itemCount", equalTo(1)).body("totalAmount", equalTo(14999.00f));
// Step 4: Checkout
RestAssured.post(baseUrl + "/checkout").then().statusCode(200).body("status", equalTo("PAID"));
// Step 5: Verify cart is empty once again
RestAssured.get(baseUrl).then().statusCode(200).body("itemCount", equalTo(0));
}
}
import pytest
import requests
from mockserver import MockServerClient, request, response, times
MOCKSERVER_HOST = "localhost"
MOCKSERVER_PORT = 1080
BASE_URL = f"http://{MOCKSERVER_HOST}:{MOCKSERVER_PORT}"
class TestMockServerSequentialState:
@pytest.fixture(autouse=True)
def setup_client(self):
self.client = MockServerClient(f"http://{MOCKSERVER_HOST}:{MOCKSERVER_PORT}")
self.client.reset()
yield
self.client.reset()
def test_payment_gateway_consecutive_states(self):
"""MockServer times() controls sequence: 1st call fails, 2nd call succeeds."""
# EXPECTATION 1: Execute exactly 1 time (times(1)) -> Return 503
self.client.expect(
request(method="POST", path="/api/v1/payout"),
response(status_code=503, body={"error": "BANK_CORE_BUSY"}),
times(1)
)
# EXPECTATION 2: Executes subsequent times -> Return 200 Settled
self.client.expect(
request(method="POST", path="/api/v1/payout"),
response(status_code=200, body={"status": "SETTLED", "referenceId": "REF-99214"}),
times(1)
)
# Act: First request triggers Expectation 1 (times=1)
res1 = requests.post(f"{BASE_URL}/api/v1/payout")
assert res1.status_code == 503
assert res1.json()["error"] == "BANK_CORE_BUSY"
# Act: Second request falls through to Expectation 2
res2 = requests.post(f"{BASE_URL}/api/v1/payout")
assert res2.status_code == 200
assert res2.json()["status"] == "SETTLED"
assert res2.json()["referenceId"] == "REF-99214"
package com.nikitainfotech.api.scenarios;
import java.util.UUID;
public class ThreadSafeScenarioFactory {
/**
* Generates a thread-isolated scenario name to prevent cross-thread state pollution
* when executing WireMock stateful tests concurrently.
*/
public static String createIsolatedScenario(String baseScenarioName) {
long threadId = Thread.currentThread().getId();
String sessionNonce = UUID.randomUUID().toString().substring(0, 8);
return String.format("%s_Thread_%d_%s", baseScenarioName, threadId, sessionNonce);
}
}
// USAGE IN TEST SUITE:
// String isolatedScenario = ThreadSafeScenarioFactory.createIsolatedScenario("ReportPolling");
// stubFor(get(urlPathEqualTo("/status"))
// .inScenario(isolatedScenario)
// .whenScenarioStateIs(STARTED)
// .willSetStateTo("PROCESSING")
// ...);
# 1. Query all active scenarios and their current state in WireMock:
curl -s -X GET "http://localhost:8089/__admin/scenarios" | jq .
# JSON RESPONSE STRUCTURE:
# {
# "scenarios": [
# {
# "id": "Async_Report_Generation",
# "name": "Async_Report_Generation",
# "state": "READY",
# "possibleStates": ["Started", "PROCESSING", "READY"]
# },
# {
# "id": "Student_Course_Cart_Workflow",
# "name": "Student_Course_Cart_Workflow",
# "state": "CHECKOUT_COMPLETE",
# "possibleStates": ["Started", "CART_POPULATED", "CHECKOUT_COMPLETE"]
# }
# ]
# }
# 2. Reset ALL scenarios back to their initial 'Started' state without deleting stubs:
curl -s -X POST "http://localhost:8089/__admin/scenarios/reset"
# 3. Reset individual scenario state via Java WireMock Client:
// WireMock.resetAllScenarios();
Feature: Stateful In-Memory Mock Server in Karate
Background:
* def port = 8085
# Initialize an in-memory state repository (shared across all incoming requests)
* def studentsDb = {}
* def counter = { value: 100 }
# 1. CREATE ENDPOINT: POST /api/v1/students
Scenario: pathMatches('/api/v1/students') && methodIs('post')
* def newId = 'STU-' + counter.value
* eval counter.value = counter.value + 1
* def record = request
* eval record.id = newId
* eval record.status = 'ENROLLED'
# Store in memory
* eval studentsDb[newId] = record
* responseStatus 201
* response = record
# 2. READ ENDPOINT: GET /api/v1/students/{id}
Scenario: pathMatches('/api/v1/students/{id}') && methodIs('get')
* def targetId = pathParams.id
* def existing = studentsDb[targetId]
# Conditional response based on in-memory state
* def isFound = existing != null
* responseStatus isFound ? 200 : 404
* response = isFound ? existing : { error: 'Student not found in memory state' }
# 3. DELETE ENDPOINT: DELETE /api/v1/students/{id}
Scenario: pathMatches('/api/v1/students/{id}') && methodIs('delete')
* def targetId = pathParams.id
* eval delete studentsDb[targetId]
* responseStatus 204
* response = ''
STATEFUL MOCKING DIRECTIVES & ARCHITECTURAL MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββββββ
β DIRECTIVE / METHOD β TOOL CONTEXT β PRIMARY PURPOSE & BEHAVIOR β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββββββββ€
β inScenario("Name") β WireMock Java / JSON β Binds stub to a named Finite State Machine β
β whenScenarioStateIs("S")β WireMock Java / JSON β Prerequisite state gate: stub matches ONLY in 'S'β
β willSetStateTo("S2") β WireMock Java / JSON β State transition: advances scenario to state 'S2'β
β Scenario.STARTED β WireMock Java Constant β The canonical default initial state of every FSM β
β resetAllScenarios() β WireMock Admin / Java β Resets all scenarios to 'Started' state β
β times(N) β MockServer Action Sequence β Limits expectation to N executions, then cascadesβ
β in-memory JS object β Karate Mock Feature β State repository surviving across HTTP calls β
β ThreadSafeScenario.. β Architecture Pattern β Appends thread ID to scenario names for safety β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββ€
β TOP 5 STATEFUL MOCKING BEST PRACTICES: β
β 1. Always start from Scenario.STARTED: Ensure every FSM scenario has a valid entry stub from STARTED. β
β 2. Reset scenarios between tests: Call resetAllScenarios() in @AfterEach to avoid state bleed. β
β 3. Isolate scenario names in parallel runs: Append thread IDs or UUIDs to avoid concurrent collisions. β
β 4. Model terminal states: Ensure your polling loop has an explicit terminal state (e.g. COMPLETED). β
β 5. Test failure transitions: Don't just test happy paths; model error transitions (e.g. FAILED, RETRY). β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ