STATEFUL MOCKING SCENARIOS: FINITE STATE MACHINES & WORKFLOW EMULATION

Architect complex state-dependent API simulations: Finite State Machine (FSM) theory, WireMock stateful scenarios, MockServer action sequences, polling loop transitions (PENDING to COMPLETED), circuit breaker trip simulations, and multi-tenant state isolation across test threads.

πŸ”„ 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.

1. Finite State Machine (FSM) Theory in Service Virtualization
The mathematical and architectural principles of modeling HTTP service virtualizations as Finite State Machines, mapping states, inputs, and state transition boundaries.
FSM State Machine Topology & Transition Dynamics
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"    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                                       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: Stateful scenarios allow a single URI (e.g. GET /jobs/42) to return completely different payloads and status codes over time as the scenario state advances, mimicking real-world asynchronous processing.
Real-Time Example 1: Asynchronous Batch Job Polling Loop (WireMock Java DSL)
Simulating an asynchronous report generation endpoint that returns 202 Accepted with progress percentages over multiple polling requests before transitioning to 200 OK with the final download URI.
Java (AsyncReportPollingScenarioTest.java)
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);
    }
}
Execution Output: Polling Attempt #1 -> Status: QUEUED (Progress: 15%) Polling Attempt #2 -> Status: BUILDING (Progress: 75%) Polling Attempt #3 -> Status: COMPLETED (Progress: 100%) PASSED: testClientPollsUntilReportGenerationCompletes The client polling loop advanced through QUEUED, BUILDING, and COMPLETED states deterministically.
Real-Time Example 2: Declarative Stateful Mappings in WireMock JSON
Configuring stateful scenarios using declarative JSON files inside the mappings/ folder for standalone WireMock or Docker instances without writing Java code.
JSON (mappings/stateful_subscription_lifecycle.json)
[
  {
    "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
      }
    }
  }
]
Mapping Rules: 1. 'scenarioName': Groups individual stub mappings into a shared Finite State Machine. 2. 'requiredScenarioState': The state required for this stub to match. 3. 'newScenarioState': The new state assigned to the scenario once this stub matches and executes.
Real-Time Example 3: Circuit Breaker Trip & Self-Healing Simulation
Simulating Resilience4j or Netflix Hystrix circuit breaker states: CLOSED (healthy), OPEN (after consecutive 500 errors, failing fast locally), and HALF-OPEN (testing recovery).
Java (CircuitBreakerStatefulSimulationTest.java)
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")));
    }
}
Resilience Verification: Enables automated verification of client-side circuit breakers, asserting that after receiving 500 and 503 errors, the client trips its circuit breaker and handles fallbacks before verifying recovery.
Real-Time Example 4: Stateful Shopping Cart CRUD Simulation in WireMock
Modeling a stateful shopping cart workflow across multiple endpoints: viewing an empty cart (GET), adding an item (POST), verifying the populated cart (GET), and checking out (DELETE).
Java (ShoppingCartWorkflowScenarioTest.java)
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));
    }
}
Stateful Multi-Endpoint Harmony: Notice that the same endpoint (GET /api/v1/cart) returned empty, then populated, then empty again based purely on the active scenario state, enabling complete end-to-end shopping cart testing without a database.
Real-Time Example 5: MockServer Action Sequences & Expectations in Python
Implementing stateful sequential responses in Python using MockServer's action sequence capabilities, returning a progression of status codes and payloads across successive calls.
Python (test_mockserver_action_sequences.py)
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"
MockServer Sequencing: In MockServer, configuring times(1) on an expectation ensures that once it matches and executes, it is removed from the active routing table, allowing the next expectation for that path to match on subsequent calls.
Real-Time Example 6: Thread-Safe State Isolation for Parallel Test Suites
When running tests in parallel, shared scenario state names can cause cross-thread collisions. This pattern isolates state by partitioning scenario names using thread IDs or dynamic session tokens.
Java (ThreadSafeScenarioFactory.java)
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")
//         ...);
Parallel Safety Rule: WireMock's scenario states are tracked globally within the server process by scenario name. In parallel test runs, appending a unique thread ID and nonce to the scenario name prevents Thread B from mutating the state machine of Thread A.
Real-Time Example 7: Programmatic Scenario Reset & State Inspection via Admin API
Inspecting and resetting active scenario states over HTTP using WireMock's RESTful Admin API, useful for debugging stuck states or resetting test environments mid-suite.
cURL & HTTP (WireMock Scenario Admin API)
# 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();
Admin Inspection Benefit: The GET /__admin/scenarios endpoint provides visibility into the exact current state of every scenario in the mock server, helping identify which transition was reached during a failed test run.
Real-Time Example 8: Stateful Mocking in Karate Framework
Implementing stateful mock server features in Karate using embedded JavaScript state containers to maintain and update in-memory data collections across successive HTTP calls.
Gherkin Feature (karate_stateful_mock.feature)
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 = ''
Karate Stateful Mock Behavior: The studentsDb JavaScript object acts as an in-memory database. A POST adds the student, a subsequent GET retrieves the exact saved data, and a DELETE removes it, mimicking a complete CRUD service with zero external databases.
Real-Time Example 9: Stateful Mocking Quick Reference Matrix
A comprehensive reference summary pairing stateful mocking concepts, WireMock FSM directives, MockServer sequences, and best practices for QA automation architects.
Stateful Mocking Concepts & Directives Matrix
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).   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Use stateful mocking to test asynchronous polling loops, multi-step checkout workflows, and circuit breaker recovery paths deterministically without relying on live, slow, or expensive backend infrastructure.