WIREMOCK STATEFUL SCENARIOS: FINITE STATE MACHINES & DYNAMIC CRUD

Architect stateful, multi-step API virtualization in REST Assured: Modeling state machines using WireMock Scenarios (Scenario.STARTED), declarative state transitions via willSetStateTo() and whenScenarioStateIs(), full CRUD entity lifecycles without a real database, asynchronous polling simulations (POLLING βž” COMPLETED), retry loops, and thread-safe scenario resets.

πŸ”„ Finite State Machines, Contextual Mutability & Dynamic API Simulation

Most real-world REST microservice workflows are fundamentally stateful. Querying an entity before registration yields a 404 Not Found; submitting a creation request changes the system state and returns 201 Created; subsequent lookups retrieve the newly populated entity; and triggering a deletion transitions the system so future requests encounter 404 or 410 Gone. Standard HTTP stubs are static and stateless: querying the same URI repeatedly returns the identical static response regardless of preceding mutations. WireMock Scenarios transform virtualization into a Deterministic Finite State Machine (FSM). By grouping stubs into named scenarios anchored at Scenario.STARTED, conditioning stub evaluation with whenScenarioStateIs(), and driving state transitions via willSetStateTo(), test automation engineers accurately simulate full CRUD lifecycles, long-running asynchronous polling jobs (Pending βž” Processing βž” Completed), and payment state machines in REST Assured without spinning up or polluting physical databases.

1. WireMock Scenario Finite State Machine Architecture
The architectural state transition diagram of a WireMock Scenario FSM, showing how successive HTTP operations mutate the active scenario state pointer and re-route subsequent requests to matching stubs.
State Machine Transition Lifecycle & State Pointer Topography
WIREMOCK SCENARIO FINITE STATE MACHINE (FSM) LIFECYCLE:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ INITIAL STATE: Scenario.STARTED (Default entry state when scenario is registered or reset)    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό (Call 1: GET /v1/students/STU-88219)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ STUB 1: whenScenarioStateIs(Scenario.STARTED) ──► No State Transition                         β”‚
β”‚ Returns: HTTP 404 Not Found {"error": "STUDENT_NOT_FOUND"}                                    β”‚
β”‚ [CONFIRMED: Entity does not exist prior to creation]                                          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό (Call 2: POST /v1/students {"id": "STU-88219", ...})
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ STUB 2: whenScenarioStateIs(Scenario.STARTED) ──► willSetStateTo("STUDENT_CREATED")           β”‚
β”‚ Returns: HTTP 201 Created {"status": "SUCCESS", "id": "STU-88219"}                            β”‚
β”‚ State Pointer Shifts: Scenario.STARTED ───────────────► "STUDENT_CREATED"                     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό (Call 3: GET /v1/students/STU-88219)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ STUB 3: whenScenarioStateIs("STUDENT_CREATED") ──► No State Transition                        β”‚
β”‚ Returns: HTTP 200 OK {"id": "STU-88219", "fullName": "Nikita Sharma", "status": "ACTIVE"}     β”‚
β”‚ [CONFIRMED: Same URI now dynamically yields populated entity!]                                β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό (Call 4: DELETE /v1/students/STU-88219)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ STUB 4: whenScenarioStateIs("STUDENT_CREATED") ──► willSetStateTo("STUDENT_DELETED")          β”‚
β”‚ Returns: HTTP 204 No Content                                                                  β”‚
β”‚ State Pointer Shifts: "STUDENT_CREATED" ──────────────► "STUDENT_DELETED"                     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό (Call 5: GET /v1/students/STU-88219)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ STUB 5: whenScenarioStateIs("STUDENT_DELETED") ──► Terminal State                             β”‚
β”‚ Returns: HTTP 404 Not Found {"error": "STUDENT_ALREADY_PURGED"}                               β”‚
β”‚ [CONFIRMED: Full CRUD lifecycle verified in-memory with zero physical database!]              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: Every WireMock scenario starts in the universal initial state Scenario.STARTED. Stubs sharing the same scenario name participate in the same state machine. Only stubs matching the current state can trigger, and invoking willSetStateTo() changes the shared state pointer immediately.
Real-Time Example 1: Full CRUD Entity Lifecycle Simulation (404 βž” 201 βž” 200 βž” 204 βž” 404)
Implementing a complete CRUD lifecycle scenario. Configures a state machine that transitions across five discrete steps: initial absence (404), entity creation (201), retrieval (200), deletion (204), and post-deletion absence (404).
Java (FullCrudScenarioTest.java State Machine Workflow)
package com.nikita.restassured.wiremock.scenarios;

import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import io.restassured.http.ContentType;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class FullCrudScenarioTest extends WireMockBaseTest {

    private static final String CRUD_SCENARIO = "Student_CRUD_Lifecycle";
    private static final String TARGET_ENDPOINT = "/v1/students/STU-88219";

    @BeforeClass
    public void setupStatefulCrudScenario() {
        // STEP 1: In state STARTED - GET returns 404 Not Found
        stubFor(get(urlEqualTo(TARGET_ENDPOINT))
                .inScenario(CRUD_SCENARIO)
                .whenScenarioStateIs(Scenario.STARTED)
                .willReturn(aResponse()
                        .withStatus(404)
                        .withHeader("Content-Type", "application/json")
                        .withBody("{\"error\": \"STUDENT_NOT_FOUND\"}")));

        // STEP 2: In state STARTED - POST creates entity and transitions state to "CREATED"
        stubFor(post(urlEqualTo("/v1/students"))
                .inScenario(CRUD_SCENARIO)
                .whenScenarioStateIs(Scenario.STARTED)
                .willSetStateTo("STUDENT_CREATED")
                .withRequestBody(matchingJsonPath("$.studentId", equalTo("STU-88219")))
                .willReturn(aResponse()
                        .withStatus(201)
                        .withHeader("Content-Type", "application/json")
                        .withBody("{\"status\": \"CREATED\", \"id\": \"STU-88219\"}")));

        // STEP 3: In state CREATED - GET now returns 200 OK with full entity payload
        stubFor(get(urlEqualTo(TARGET_ENDPOINT))
                .inScenario(CRUD_SCENARIO)
                .whenScenarioStateIs("STUDENT_CREATED")
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody("{\n" +
                                "  \"id\": \"STU-88219\",\n" +
                                "  \"fullName\": \"Nikita Sharma\",\n" +
                                "  \"academicTrack\": \"ENTERPRISE_AUTOMATION\",\n" +
                                "  \"enrolledCredits\": 16,\n" +
                                "  \"status\": \"ACTIVE\"\n" +
                                "}")));

        // STEP 4: In state CREATED - DELETE purges entity and transitions state to "DELETED"
        stubFor(delete(urlEqualTo(TARGET_ENDPOINT))
                .inScenario(CRUD_SCENARIO)
                .whenScenarioStateIs("STUDENT_CREATED")
                .willSetStateTo("STUDENT_DELETED")
                .willReturn(aResponse()
                        .withStatus(204)));

        // STEP 5: In state DELETED - GET returns 404 confirming deletion
        stubFor(get(urlEqualTo(TARGET_ENDPOINT))
                .inScenario(CRUD_SCENARIO)
                .whenScenarioStateIs("STUDENT_DELETED")
                .willReturn(aResponse()
                        .withStatus(404)
                        .withHeader("Content-Type", "application/json")
                        .withBody("{\"error\": \"STUDENT_PURGED_ALREADY\"}")));

        System.out.println("[*] Configured 5-step CRUD Finite State Machine in WireMock.");
    }

    @Test(description = "Execute full 5-stage CRUD workflow and verify state transitions in sequence")
    public void testCompleteCrudLifecycleWorkflow() {
        // Stage 1: Verify entity does not exist initially (404)
        given().spec(mockSpec).get(TARGET_ENDPOINT)
                .then().statusCode(404).body("error", equalTo("STUDENT_NOT_FOUND"));
        System.out.println("[Stage 1 Pass] Initial GET returned expected 404 Not Found.");

        // Stage 2: Create entity via POST (201) -> State advances to STUDENT_CREATED
        String createPayload = "{\"studentId\": \"STU-88219\", \"fullName\": \"Nikita Sharma\"}";
        given().spec(mockSpec).body(createPayload).post("/v1/students")
                .then().statusCode(201).body("status", equalTo("CREATED"));
        System.out.println("[Stage 2 Pass] POST created student entity (State βž” STUDENT_CREATED).");

        // Stage 3: Query same endpoint -> Verify 200 OK with populated profile
        given().spec(mockSpec).get(TARGET_ENDPOINT)
                .then().statusCode(200)
                .body("id", equalTo("STU-88219"))
                .body("fullName", equalTo("Nikita Sharma"))
                .body("status", equalTo("ACTIVE"));
        System.out.println("[Stage 3 Pass] Secondary GET returned 200 OK with active profile.");

        // Stage 4: Delete entity via DELETE (204) -> State advances to STUDENT_DELETED
        given().spec(mockSpec).delete(TARGET_ENDPOINT)
                .then().statusCode(204);
        System.out.println("[Stage 4 Pass] DELETE executed successfully (State βž” STUDENT_DELETED).");

        // Stage 5: Final GET -> Verify 404 confirming entity is permanently purged
        given().spec(mockSpec).get(TARGET_ENDPOINT)
                .then().statusCode(404).body("error", equalTo("STUDENT_PURGED_ALREADY"));
        System.out.println("[Stage 5 Pass] Final GET verified entity is permanently absent.");
    }
}
Scenario Execution Output: GET /v1/students/STU-88219 [STARTED] ──► HTTP 404 (STUDENT_NOT_FOUND) POST /v1/students [STARTED] ──► HTTP 201 Created [State βž” STUDENT_CREATED] GET /v1/students/STU-88219 [STUDENT_CREATED] ──► HTTP 200 OK (Nikita Sharma) DELETE /v1/students/STU-88219 [STUDENT_CREATED] ──► HTTP 204 No Content [State βž” STUDENT_DELETED] GET /v1/students/STU-88219 [STUDENT_DELETED] ──► HTTP 404 (STUDENT_PURGED_ALREADY) PASSED: testCompleteCrudLifecycleWorkflow
Real-Time Example 2: Asynchronous Polling Job Simulation (PENDING βž” PROCESSING βž” COMPLETED)
Virtualizing asynchronous long-running background tasks. Models a batch job endpoint where consecutive GET requests return progressing job statusesβ€”PENDING on poll 1, PROCESSING on poll 2, and COMPLETED on poll 3.
Java (AsyncJobPollingScenarioTest.java State Machine)
package com.nikita.restassured.wiremock.scenarios;

import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class AsyncJobPollingScenarioTest extends WireMockBaseTest {

    private static final String ASYNC_SCENARIO = "Async_Report_Generation";
    private static final String JOB_ENDPOINT = "/v1/reports/batch-job-994";

    @BeforeClass
    public void setupAsyncPollingScenario() {
        // POLL 1: In state STARTED - Job is initialized (PENDING) -> advances state to "PROCESSING"
        stubFor(get(urlEqualTo(JOB_ENDPOINT))
                .inScenario(ASYNC_SCENARIO)
                .whenScenarioStateIs(Scenario.STARTED)
                .willSetStateTo("JOB_PROCESSING")
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody("{\"jobId\": \"batch-job-994\", \"status\": \"PENDING\", \"progress\": 0}")));

        // POLL 2: In state PROCESSING - Job is actively executing -> advances state to "COMPLETED"
        stubFor(get(urlEqualTo(JOB_ENDPOINT))
                .inScenario(ASYNC_SCENARIO)
                .whenScenarioStateIs("JOB_PROCESSING")
                .willSetStateTo("JOB_COMPLETED")
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody("{\"jobId\": \"batch-job-994\", \"status\": \"PROCESSING\", \"progress\": 55}")));

        // POLL 3+: In state COMPLETED - Job finished successfully with report download link
        stubFor(get(urlEqualTo(JOB_ENDPOINT))
                .inScenario(ASYNC_SCENARIO)
                .whenScenarioStateIs("JOB_COMPLETED")
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody("{\n" +
                                "  \"jobId\": \"batch-job-994\",\n" +
                                "  \"status\": \"COMPLETED\",\n" +
                                "  \"progress\": 100,\n" +
                                "  \"downloadUrl\": \"https://storage.nikita-infotech.com/reports/batch-994.pdf\"\n" +
                                "}")));
    }

    @Test(description = "Verify client polling loop drives scenario through PENDING, PROCESSING, and COMPLETED states")
    public void testAsyncReportPollingLoop() {
        // Poll 1: Expect PENDING
        given().spec(mockSpec).get(JOB_ENDPOINT)
                .then().statusCode(200)
                .body("status", equalTo("PENDING"))
                .body("progress", equalTo(0));
        System.out.println("[Poll 1] Status: PENDING (0%) -> State shifted to JOB_PROCESSING.");

        // Poll 2: Expect PROCESSING
        given().spec(mockSpec).get(JOB_ENDPOINT)
                .then().statusCode(200)
                .body("status", equalTo("PROCESSING"))
                .body("progress", equalTo(55));
        System.out.println("[Poll 2] Status: PROCESSING (55%) -> State shifted to JOB_COMPLETED.");

        // Poll 3: Expect COMPLETED with downloadUrl
        given().spec(mockSpec).get(JOB_ENDPOINT)
                .then().statusCode(200)
                .body("status", equalTo("COMPLETED"))
                .body("progress", equalTo(100))
                .body("downloadUrl", equalTo("https://storage.nikita-infotech.com/reports/batch-994.pdf"));
        System.out.println("[Poll 3] Status: COMPLETED (100%) -> Final artifact URL verified.");
    }
}
Async Polling Telemetry: [Poll 1] GET /v1/reports/batch-job-994 ──► Status: PENDING (0%) [Poll 2] GET /v1/reports/batch-job-994 ──► Status: PROCESSING (55%) [Poll 3] GET /v1/reports/batch-job-994 ──► Status: COMPLETED (100%) [Artifact Available] Simulates asynchronous polling progression deterministically without time-dependent race conditions.
Real-Time Example 3: Transient Failure & Automated Retry Resilience Simulation
Verifying client-side retry middleware. Simulates transient infrastructure instability: Call 1 returns 503 Service Unavailable, Call 2 returns 503, and Call 3 succeeds with 200 OK, confirming that retry interceptors self-heal gracefully.
Java (TransientRetryScenarioTest.java Self-Healing Simulation)
package com.nikita.restassured.wiremock.scenarios;

import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import org.testng.Assert;
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 TransientRetryScenarioTest extends WireMockBaseTest {

    private static final String RETRY_SCENARIO = "Transient_Service_Failure";
    private static final String FLAKY_ENDPOINT = "/v1/external/flaky-gateway";

    @BeforeClass
    public void setupTransientFailureScenario() {
        // ATTEMPT 1: STARTED state -> Fails with 503 Service Unavailable -> advances to RETRY_1
        stubFor(get(urlEqualTo(FLAKY_ENDPOINT))
                .inScenario(RETRY_SCENARIO)
                .whenScenarioStateIs(Scenario.STARTED)
                .willSetStateTo("FIRST_RETRY")
                .willReturn(aResponse()
                        .withStatus(503)
                        .withHeader("Retry-After", "1")
                        .withBody("{\"error\": \"SERVICE_OVERLOADED_1\"}")));

        // ATTEMPT 2: FIRST_RETRY state -> Fails again with 503 -> advances to RETRY_2
        stubFor(get(urlEqualTo(FLAKY_ENDPOINT))
                .inScenario(RETRY_SCENARIO)
                .whenScenarioStateIs("FIRST_RETRY")
                .willSetStateTo("SECOND_RETRY")
                .willReturn(aResponse()
                        .withStatus(503)
                        .withHeader("Retry-After", "1")
                        .withBody("{\"error\": \"SERVICE_OVERLOADED_2\"}")));

        // ATTEMPT 3: SECOND_RETRY state -> Recovers and succeeds with 200 OK
        stubFor(get(urlEqualTo(FLAKY_ENDPOINT))
                .inScenario(RETRY_SCENARIO)
                .whenScenarioStateIs("SECOND_RETRY")
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody("{\"status\": \"HEALED_SUCCESS\"}")));
    }

    @Test(description = "Verify client retry loop survives two consecutive 503s and captures recovery on 3rd attempt")
    public void testTransientRetryRecovery() {
        int maxRetries = 3;
        int attempt = 0;
        int finalStatusCode = 0;

        while (attempt < maxRetries) {
            attempt++;
            System.out.println("[*] Dispatching request attempt: " + attempt);

            int status = given()
                    .spec(mockSpec)
                .when()
                    .get(FLAKY_ENDPOINT)
                .then()
                    .extract().statusCode();

            if (status == 200) {
                finalStatusCode = 200;
                System.out.printf("[βœ”] Request succeeded on attempt %d with HTTP 200 OK.%n", attempt);
                break;
            } else if (status == 503) {
                System.out.printf("[!] Attempt %d failed with HTTP 503. Retrying...%n", attempt);
            }
        }

        Assert.assertEquals(finalStatusCode, 200, "Retry mechanism failed to recover within max attempts!");
        Assert.assertEquals(attempt, 3, "Expected exactly 3 attempts before recovery!");
    }
}
Transient Recovery Trace: [*] Dispatching request attempt: 1 [!] Attempt 1 failed with HTTP 503. Retrying... (State βž” FIRST_RETRY) [*] Dispatching request attempt: 2 [!] Attempt 2 failed with HTTP 503. Retrying... (State βž” SECOND_RETRY) [*] Dispatching request attempt: 3 [βœ”] Request succeeded on attempt 3 with HTTP 200 OK. PASSED: testTransientRetryRecovery
Real-Time Example 4: Resetting Scenario State via resetScenarios() & setScenarioState()
Managing scenario state programmatically. Demonstrates using wireMockServer.resetScenarios() to restore all scenarios back to Scenario.STARTED in @BeforeMethod, and forcing explicit state via setScenarioState() for targeted sub-tests.
Java (ScenarioResetAndStateSeedingTest.java State Governance)
package com.nikita.restassured.wiremock.scenarios;

import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class ScenarioResetAndStateSeedingTest extends WireMockBaseTest {

    private static final String ACCOUNT_SCENARIO = "Bank_Account_Lifecycle";

    @BeforeMethod(alwaysRun = true)
    public void resetScenarioStateMachine() {
        // Resets all state machines back to Scenario.STARTED between every test method
        wireMockServer.resetScenarios();
        System.out.println("[*] wireMockServer.resetScenarios() executed: All FSMs reset to Scenario.STARTED.");

        // Define stateful account stubs
        stubFor(get(urlEqualTo("/v1/account/status"))
                .inScenario(ACCOUNT_SCENARIO)
                .whenScenarioStateIs(Scenario.STARTED)
                .willReturn(aResponse().withStatus(200).withBody("{\"account\": \"ACTIVE\"}")));

        stubFor(get(urlEqualTo("/v1/account/status"))
                .inScenario(ACCOUNT_SCENARIO)
                .whenScenarioStateIs("FROZEN")
                .willReturn(aResponse().withStatus(403).withBody("{\"account\": \"FROZEN_RESTRICTED\"}")));
    }

    @Test(description = "Verify natural state execution starting from Scenario.STARTED")
    public void testDefaultStartedState() {
        given().spec(mockSpec).get("/v1/account/status")
                .then().statusCode(200).body("account", equalTo("ACTIVE"));

        System.out.println("[βœ”] Verified default ACTIVE state.");
    }

    @Test(description = "Verify programmatic state seeding: jump directly to FROZEN state")
    public void testForcedStateSeeding() {
        // Programmatically fast-forward the state machine to "FROZEN" without running prerequisite calls:
        wireMockServer.setScenarioState(ACCOUNT_SCENARIO, "FROZEN");
        System.out.println("[*] Forced scenario state to 'FROZEN' via wireMockServer.setScenarioState().");

        given().spec(mockSpec).get("/v1/account/status")
                .then().statusCode(403).body("account", equalTo("FROZEN_RESTRICTED"));

        System.out.println("[βœ”] Successfully executed test against seeded 'FROZEN' state.");
    }
}
State Reset & Seeding Telemetry: Test 1: resetScenarios() ──► State is Scenario.STARTED ──► GET returns 200 (ACTIVE) Test 2: resetScenarios() ──► setScenarioState("FROZEN") ──► GET returns 403 (FROZEN_RESTRICTED) Programmatic state seeding enables targeted testing of terminal states without executing lengthy multi-step setups.
Real-Time Example 5: Banking Payment Approval Workflow FSM (INITIATED βž” PENDING_OTP βž” AUTHORIZED βž” SETTLED)
Modeling a real-world multi-stage financial transaction. Simulates an e-commerce checkout flow across four state transitions: payment initiated, OTP challenge, authorization approval, and final fund settlement.
Java (PaymentFsmWorkflowTest.java Multi-Stage Financial Flow)
package com.nikita.restassured.wiremock.scenarios;

import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import io.restassured.http.ContentType;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class PaymentFsmWorkflowTest extends WireMockBaseTest {

    private static final String PAYMENT_FSM = "Payment_Processing_Pipeline";
    private static final String TXN_ID = "TXN-77412";

    @BeforeClass
    public void setupPaymentStateMachine() {
        // STATE 1 (STARTED): Initiate Payment -> advances to PENDING_OTP
        stubFor(post(urlEqualTo("/v1/payments/initiate"))
                .inScenario(PAYMENT_FSM)
                .whenScenarioStateIs(Scenario.STARTED)
                .willSetStateTo("PENDING_OTP")
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody("{\"txnId\": \"" + TXN_ID + "\", \"state\": \"PENDING_OTP\"}")));

        // STATE 2 (PENDING_OTP): Submit OTP -> advances to AUTHORIZED
        stubFor(post(urlEqualTo("/v1/payments/" + TXN_ID + "/submit-otp"))
                .inScenario(PAYMENT_FSM)
                .whenScenarioStateIs("PENDING_OTP")
                .willSetStateTo("AUTHORIZED")
                .withRequestBody(matchingJsonPath("$.otp", equalTo("411015")))
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody("{\"txnId\": \"" + TXN_ID + "\", \"state\": \"AUTHORIZED\"}")));

        // STATE 3 (AUTHORIZED): Capture Funds -> advances to SETTLED
        stubFor(post(urlEqualTo("/v1/payments/" + TXN_ID + "/capture"))
                .inScenario(PAYMENT_FSM)
                .whenScenarioStateIs("AUTHORIZED")
                .willSetStateTo("SETTLED")
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody("{\"txnId\": \"" + TXN_ID + "\", \"state\": \"SETTLED\"}")));

        // STATE 4 (SETTLED): Query Final Status
        stubFor(get(urlEqualTo("/v1/payments/" + TXN_ID))
                .inScenario(PAYMENT_FSM)
                .whenScenarioStateIs("SETTLED")
                .willReturn(aResponse()
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody("{\"txnId\": \"" + TXN_ID + "\", \"state\": \"SETTLED\", \"cleared\": true}")));
    }

    @Test(description = "Execute multi-stage financial payment workflow through OTP and settlement")
    public void testFinancialPaymentLifecycleFsm() {
        // Step 1: Initiate payment
        given().spec(mockSpec).body("{\"amount\": 1500.00, \"currency\": \"INR\"}").post("/v1/payments/initiate")
                .then().statusCode(200).body("state", equalTo("PENDING_OTP"));
        System.out.println("[Step 1] Payment initiated. OTP challenge triggered.");

        // Step 2: Submit valid OTP
        given().spec(mockSpec).body("{\"otp\": \"411015\"}").post("/v1/payments/" + TXN_ID + "/submit-otp")
                .then().statusCode(200).body("state", equalTo("AUTHORIZED"));
        System.out.println("[Step 2] OTP validated. Transaction AUTHORIZED.");

        // Step 3: Capture authorized funds
        given().spec(mockSpec).post("/v1/payments/" + TXN_ID + "/capture")
                .then().statusCode(200).body("state", equalTo("SETTLED"));
        System.out.println("[Step 3] Funds captured. Transaction SETTLED.");

        // Step 4: Verify ledger status
        given().spec(mockSpec).get("/v1/payments/" + TXN_ID)
                .then().statusCode(200)
                .body("state", equalTo("SETTLED"))
                .body("cleared", equalTo(true));
        System.out.println("[Step 4] Final ledger query confirmed: Transaction cleared successfully.");
    }
}
Payment Workflow Output: POST /v1/payments/initiate -> HTTP 200 OK [state: PENDING_OTP] POST /v1/payments/TXN-77412/submit-otp -> HTTP 200 OK [state: AUTHORIZED] POST /v1/payments/TXN-77412/capture -> HTTP 200 OK [state: SETTLED] GET /v1/payments/TXN-77412 -> HTTP 200 OK [state: SETTLED, cleared: true] PASSED: testFinancialPaymentLifecycleFsm
Real-Time Example 6: Declarative JSON Mapping Files for Stateful Scenarios
Configuring stateful scenarios via static JSON files. Demonstrates authoring JSON mapping files in mappings/ using scenarioName, requiredScenarioState, and newScenarioState attributes.
JSON (mappings/student-order-scenario-files.json)
# ==============================================================================
# FILE 1: src/test/resources/mappings/order-state-1-get-empty.json
# ==============================================================================
{
  "scenarioName": "Order_Processing_Scenario",
  "requiredScenarioState": "Started",
  "request": {
    "method": "GET",
    "url": "/v1/orders/ORD-101"
  },
  "response": {
    "status": 404,
    "headers": { "Content-Type": "application/json" },
    "jsonBody": { "error": "ORDER_NOT_FOUND" }
  }
}

# ==============================================================================
# FILE 2: src/test/resources/mappings/order-state-2-post-create.json
# ==============================================================================
{
  "scenarioName": "Order_Processing_Scenario",
  "requiredScenarioState": "Started",
  "newScenarioState": "ORDER_PLACED",
  "request": {
    "method": "POST",
    "url": "/v1/orders",
    "bodyPatterns": [
      { "matchesJsonPath": "$.orderId" }
    ]
  },
  "response": {
    "status": 201,
    "headers": { "Content-Type": "application/json" },
    "jsonBody": { "status": "ORDER_CREATED", "orderId": "ORD-101" }
  }
}

# ==============================================================================
# FILE 3: src/test/resources/mappings/order-state-3-get-placed.json
# ==============================================================================
{
  "scenarioName": "Order_Processing_Scenario",
  "requiredScenarioState": "ORDER_PLACED",
  "request": {
    "method": "GET",
    "url": "/v1/orders/ORD-101"
  },
  "response": {
    "status": 200,
    "headers": { "Content-Type": "application/json" },
    "jsonBody": { "orderId": "ORD-101", "fulfillmentStatus": "PENDING_DISPATCH" }
  }
}
Filesystem Scenario Benefits: - scenarioName: Associates independent JSON files into a unified finite state machine. - requiredScenarioState: Maps to whenScenarioStateIs() in Java DSL. - newScenarioState: Maps to willSetStateTo() in Java DSL. Allows teams to maintain stateful workflows directly in Git as declarative JSON artifacts.
Real-Time Example 7: Thread-Safe Parallel Execution with Unique Scenario Names
Preventing race conditions during parallel test runs. Demonstrates dynamically parameterizing scenario names using thread IDs or UUIDs (e.g. "Scenario_" + Thread.currentThread().getId()) so concurrent TestNG workers maintain completely isolated state machines.
Java (ThreadIsolatedScenarioTest.java Parallel State Isolation)
package com.nikita.restassured.wiremock.scenarios;

import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import org.testng.annotations.Test;

import java.util.UUID;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class ThreadIsolatedScenarioTest extends WireMockBaseTest {

    // ==========================================================================
    // THREAD-SAFETY PRINCIPLE FOR WIREMOCK SCENARIOS:
    // If multiple threads run a scenario named "Order_Flow" concurrently, Thread A
    // might advance the state to "CREATED" while Thread B still expects "STARTED"!
    //
    // SOLUTION: Use unique per-thread or per-test scenario names!
    // ==========================================================================

    @Test(threadPoolSize = 2, invocationCount = 2, description = "Run parallel state machines with isolated scenario namespaces")
    public void testParallelStateIsolation() {
        long threadId = Thread.currentThread().getId();
        String uniqueStudentId = "STU-THREAD-" + threadId;
        String threadScenarioName = "Scenario_Thread_" + threadId + "_" + UUID.randomUUID().toString().substring(0, 6);

        System.out.printf("[Thread-%d] Initializing isolated scenario: %s for entity: %s%n",
                threadId, threadScenarioName, uniqueStudentId);

        // Step 1: Initial empty state for this thread's entity
        stubFor(get(urlEqualTo("/v1/threads/" + uniqueStudentId))
                .inScenario(threadScenarioName)
                .whenScenarioStateIs(Scenario.STARTED)
                .willReturn(aResponse().withStatus(404).withBody("{\"status\": \"EMPTY\"}")));

        // Step 2: Mutation advances this thread's state to POPULATED
        stubFor(post(urlEqualTo("/v1/threads/" + uniqueStudentId))
                .inScenario(threadScenarioName)
                .whenScenarioStateIs(Scenario.STARTED)
                .willSetStateTo("POPULATED")
                .willReturn(aResponse().withStatus(201).withBody("{\"status\": \"SAVED\"}")));

        // Step 3: Query returns populated state
        stubFor(get(urlEqualTo("/v1/threads/" + uniqueStudentId))
                .inScenario(threadScenarioName)
                .whenScenarioStateIs("POPULATED")
                .willReturn(aResponse().withStatus(200).withBody("{\"status\": \"ACTIVE_ON_THREAD\"}")));

        // Execute thread-isolated workflow
        given().spec(mockSpec).get("/v1/threads/" + uniqueStudentId)
                .then().statusCode(404);

        given().spec(mockSpec).post("/v1/threads/" + uniqueStudentId)
                .then().statusCode(201);

        given().spec(mockSpec).get("/v1/threads/" + uniqueStudentId)
                .then().statusCode(200).body("status", equalTo("ACTIVE_ON_THREAD"));

        System.out.printf("[βœ” Thread-%d] Completed stateful workflow with zero cross-thread state bleed.%n", threadId);
    }
}
Parallel Concurrency Output: [Thread-21] Initializing isolated scenario: Scenario_Thread_21_4f8a10 for entity: STU-THREAD-21 [Thread-22] Initializing isolated scenario: Scenario_Thread_22_a9b2c3 for entity: STU-THREAD-22 [βœ” Thread-21] Completed stateful workflow with zero cross-thread state bleed. [βœ” Thread-22] Completed stateful workflow with zero cross-thread state bleed. Dynamic namespacing ensures each parallel test runner manages its own state pointer.
Real-Time Example 8: Debugging Scenario Deadlocks & State Desynchronization Triage
Troubleshooting scenario state machine defects: diagnosing unexpected 404 Not Found errors caused by state desynchronization, inspecting the active scenario state via getAllScenarios(), and resolving deadlocks.
Java (Triage: Diagnosing Scenario State Desynchronization)
package com.nikita.restassured.wiremock.scenarios;

import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.List;

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

public class ScenarioTriageTest extends WireMockBaseTest {

    // ==========================================================================
    // COMMON PITFALL: STATE DESYNCHRONIZATION (UNMATCHED 404)
    // Symptom: The test dispatches a request expecting Stub B, but WireMock returns
    // 404 Not Found!
    // CAUSE: The scenario never transitioned to the state required by Stub B,
    // or an intermediate call failed and left the state pointer in an unexpected state.
    //
    // FIX: Inspect the live scenario state via wireMockServer.getAllScenarios()!
    // ==========================================================================

    @Test(description = "Demonstrate diagnosing active scenario state using WireMock inspection APIs")
    public void testDiagnoseScenarioStateMismatch() {
        String triageScenario = "Triage_Scenario_FSM";

        stubFor(get(urlEqualTo("/v1/triage/step1"))
                .inScenario(triageScenario)
                .whenScenarioStateIs(Scenario.STARTED)
                .willSetStateTo("STEP_ONE_DONE")
                .willReturn(aResponse().withStatus(200)));

        stubFor(get(urlEqualTo("/v1/triage/step2"))
                .inScenario(triageScenario)
                .whenScenarioStateIs("STEP_ONE_DONE")
                .willSetStateTo("STEP_TWO_DONE")
                .willReturn(aResponse().withStatus(200)));

        // Call step 1: State advances to STEP_ONE_DONE
        given().spec(mockSpec).get("/v1/triage/step1").then().statusCode(200);

        // Inspect scenario registry in memory:
        List<Scenario> allScenarios = wireMockServer.getAllScenarios().getScenarios();
        Scenario activeScenario = allScenarios.stream()
                .filter(s -> s.getName().equals(triageScenario))
                .findFirst()
                .orElseThrow(() -> new AssertionError("Scenario not found!"));

        System.out.println("---------------- WIREMOCK SCENARIO AUDIT ----------------");
        System.out.println("Scenario Name : " + activeScenario.getName());
        System.out.println("Current State : " + activeScenario.getState());
        System.out.println("---------------------------------------------------------");

        // Verify current state is as expected:
        Assert.assertEquals(activeScenario.getState(), "STEP_ONE_DONE", 
                "Scenario state must be STEP_ONE_DONE after calling step1!");
    }
}
Triage Diagnostic Report: ---------------- WIREMOCK SCENARIO AUDIT ---------------- Scenario Name : Triage_Scenario_FSM Current State : STEP_ONE_DONE --------------------------------------------------------- Calling wireMockServer.getAllScenarios() exposes active state pointers immediately without blind guesswork.
Real-Time Example 9: WireMock Stateful Scenarios Specification Reference Matrix
A comprehensive reference summary pairing WireMock scenario methods, state machine keywords, transition rules, and operational best practices for REST Assured automation architects.
Stateful Scenarios Specification Reference Matrix
WIREMOCK STATEFUL SCENARIOS SPECIFICATION MATRIX:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ SCENARIO CONSTRUCT      β”‚ DSL SYNTAX EXAMPLE           β”‚ PARAMETER TYPE   β”‚ PRIMARY OPERATIONAL PURPOSE   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ inScenario              β”‚ .inScenario("ScenarioName")  β”‚ String (Name)    β”‚ Groups stubs into shared FSM  β”‚
β”‚ whenScenarioStateIs     β”‚ .whenScenarioStateIs("STATE")β”‚ String (State)   β”‚ Pre-condition state filter    β”‚
β”‚ willSetStateTo          β”‚ .willSetStateTo("NEW_STATE") β”‚ String (State)   β”‚ Post-execution transition     β”‚
β”‚ Scenario.STARTED        β”‚ Scenario.STARTED ("Started") β”‚ Constant String  β”‚ Default universal entry state β”‚
β”‚ resetScenarios()        β”‚ wireMockServer.resetScenariosβ”‚ Method Call      β”‚ Restores all FSMs to Started  β”‚
β”‚ setScenarioState()      β”‚ setScenarioState(name, state)β”‚ Method Call      β”‚ Seeds explicit state directly β”‚
β”‚ getAllScenarios()       β”‚ wireMockServer.getAllScenarioβ”‚ Diagnostic Query β”‚ Returns active state pointers β”‚
β”‚ JSON: scenarioName      β”‚ "scenarioName": "Order_Flow" β”‚ JSON Property    β”‚ Groups filesystem JSON stubs  β”‚
β”‚ JSON: requiredState     β”‚ "requiredScenarioState": ".."β”‚ JSON Property    β”‚ Pre-condition state in JSON   β”‚
β”‚ JSON: newState          β”‚ "newScenarioState": "ACTIVE" β”‚ JSON Property    β”‚ State transition in JSON      β”‚
β”‚ Thread Isolation        β”‚ "Scenario_" + threadId       β”‚ Dynamic String   β”‚ Prevents parallel collisions  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ TOP 5 WIREMOCK SCENARIO BEST PRACTICES:                                                                   β”‚
β”‚ 1. Always reset scenarios in @BeforeMethod: Call wireMockServer.resetScenarios() to prevent leakage.      β”‚
β”‚ 2. Use dynamic scenario names for parallel tests: Namespace with Thread IDs or UUIDs to avoid races.      β”‚
β”‚ 3. Model asynchronous polling with multi-step FSMs: Test PENDING βž” PROCESSING βž” COMPLETED cleanly.      β”‚  
β”‚ 4. Seed terminal states directly via setScenarioState(): Test error and frozen states without setup.      β”‚
β”‚ 5. Inspect getAllScenarios() on unexpected 404s: Verify current state pointer during test triage.         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: WireMock stateful scenarios elevate API virtualization into dynamic Finite State Machines. By chaining inScenario(), whenScenarioStateIs(), and willSetStateTo() across REST Assured test suites, resetting state in @BeforeMethod teardowns, and namespacing scenarios for thread safety, you build reliable, production-grade test automation that validates complex stateful workflows without depending on live databases.