π 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.
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!] β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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.");
}
}
PENDING on poll 1, PROCESSING on poll 2, and COMPLETED on poll 3.
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.");
}
}
503 Service Unavailable, Call 2 returns 503, and Call 3 succeeds with 200 OK, confirming that retry interceptors self-heal gracefully.
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!");
}
}
wireMockServer.resetScenarios() to restore all scenarios back to Scenario.STARTED in @BeforeMethod, and forcing explicit state via setScenarioState() for targeted sub-tests.
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.");
}
}
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.");
}
}
mappings/ using scenarioName, requiredScenarioState, and newScenarioState attributes.
# ==============================================================================
# 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" }
}
}
"Scenario_" + Thread.currentThread().getId()) so concurrent TestNG workers maintain completely isolated state machines.
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);
}
}
404 Not Found errors caused by state desynchronization, inspecting the active scenario state via getAllScenarios(), and resolving deadlocks.
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!");
}
}
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. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ