π― Predicate Engines, Conflict Resolution & Hierarchical Routing Cascades
In enterprise service virtualization, static 1-to-1 endpoint stubs (such as matching an exact URL like urlEqualTo("/students/1")) quickly become unwieldy when testing complex test matrices with dynamic query parameters, varying tenant headers, and polymorphic JSON payloads. Real-world microservice environments require Dynamic Request Matching capable of inspecting URL segments via regular expressions, querying JSON tree structures with JSONPath predicate filters, asserting the presence or absence of security tokens, and resolving overlapping stub definitions. When multiple stubs match an incoming HTTP request simultaneously, WireMock's Priority Evaluation Engine dictates which mock response executes. By assigning numerical priorities with atPriority(n), automation engineers configure specific high-priority stubs (e.g., handling edge-case VIP accounts or negative boundary failures) while maintaining a lower-priority catch-all default stub, eliminating brittle test setups and redundant mock registrations in REST Assured.
INCOMING HTTP WIRE REQUEST DISPATCH:
POST /v1/students/STU-88219/courses?academicYear=2026
Headers: Authorization: Bearer ey..., X-Tenant-Tier: PREMIUM
Body: {"courseCode": "REST-JAVA-201", "credits": 4, "overrideCapacity": true}
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β WIREMOCK PREDICATE EVALUATION ENGINE β
β βββ 1. URL Path / Query Predicate: urlPathMatching("/v1/students/[A-Z0-9-]+/courses") β
β β βββ withQueryParam("academicYear", matching("202[0-9]")) β
β βββ 2. Header Predicates: β
β β βββ withHeader("Authorization", matching("^Bearer\\s[a-zA-Z0-9._-]+$")) β
β β βββ withHeader("X-Tenant-Tier", equalTo("PREMIUM")) β
β βββ 3. Body JSONPath Predicates: β
β βββ matchingJsonPath("$.[?(@.credits >= 3)]") β
β βββ matchingJsonPath("$.overrideCapacity", equalTo("true")) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββ
βΌ (Candidate Stubs Matching Predicates) βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β CANDIDATE STUB A: atPriority(1) [HIGH] β β CANDIDATE STUB B: atPriority(5) [FALLBACK] β
ββββββββββββββββββββββββββββββββββββββββββββββββ€ ββββββββββββββββββββββββββββββββββββββββββββββββ€
β Match criteria: Specific VIP course override β β Match criteria: General course enrollment β
β Priority Rank: 1 (Lowest integer = Highest) β β Priority Rank: 5 (Lower priority fallback) β
β [SELECTED & EXECUTED] β β [IGNORED DUE TO PRIORITY RULES] β
β Returns: HTTP 200 OK (Capacity Overridden) β β Returns: HTTP 201 Created (Standard Flow) β
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Wire Packet Returned to REST Assured)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β REST ASSURED RESPONSE ENGINE: .then().statusCode(200).body("status", equalTo("OVERRIDDEN")) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
urlEqualTo), full regex evaluation including query parameters (urlMatching), and path-only regex matching decoupled from query parameters (urlPathMatching).
package com.nikita.restassured.wiremock.matching;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import io.restassured.http.ContentType;
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 UrlMatchingOperatorsTest extends WireMockBaseTest {
// =========================================================================
// 1. urlEqualTo: Matches EXACT literal URI including query string ordering
// =========================================================================
@Test(description = "Demonstrate urlEqualTo exact matching")
public void testUrlEqualTo() {
stubFor(get(urlEqualTo("/v1/students/exact-match?active=true"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"type\": \"EXACT_URL_MATCH\"}")));
given()
.spec(mockSpec)
.when()
.get("/v1/students/exact-match?active=true")
.then()
.statusCode(200)
.body("type", equalTo("EXACT_URL_MATCH"));
System.out.println("[β] urlEqualTo verified.");
}
// =========================================================================
// 2. urlPathMatching: Matches PATH using regex, ignoring query string completely
// =========================================================================
@Test(description = "Demonstrate urlPathMatching regex path matching with dynamic query parameters")
public void testUrlPathMatching() {
// Regex matches any student ID pattern: /v1/students/STU-[0-9]{5}
stubFor(get(urlPathMatching("/v1/students/STU-[0-9]{5}"))
.withQueryParam("semester", matching("FALL|SPRING|SUMMER"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"type\": \"REGEX_PATH_MATCH\"}")));
given()
.spec(mockSpec)
.queryParam("semester", "FALL")
.queryParam("untrackedFilter", "randomValue") // Extra query params are ignored by urlPathMatching
.when()
.get("/v1/students/STU-88219")
.then()
.statusCode(200)
.body("type", equalTo("REGEX_PATH_MATCH"));
System.out.println("[β] urlPathMatching verified.");
}
// =========================================================================
// 3. urlMatching: Matches ENTIRE URI (path + query string) using a single regex
// =========================================================================
@Test(description = "Demonstrate urlMatching regex covering entire URL string")
public void testUrlMatchingEntireString() {
stubFor(get(urlMatching("/v1/reports/[0-9]+\\?format=(pdf|csv)&page=[0-9]+"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"type\": \"FULL_REGEX_MATCH\"}")));
given()
.spec(mockSpec)
.when()
.get("/v1/reports/99412?format=pdf&page=2")
.then()
.statusCode(200)
.body("type", equalTo("FULL_REGEX_MATCH"));
System.out.println("[β] urlMatching verified.");
}
}
equalTo, matching), asserts header absence (absent()), evaluates multi-value headers, and inspects authentication cookies.
package com.nikita.restassured.wiremock.matching;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import io.restassured.http.ContentType;
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 HeaderAndCookieMatchingTest extends WireMockBaseTest {
@Test(description = "Stub asserting valid Bearer token syntax, mandatory tenant header, and session cookie")
public void testHeaderAndCookieMatching() {
stubFor(get(urlPathEqualTo("/v1/secure/profile"))
// Header 1: Bearer token must match JWT regex syntax
.withHeader("Authorization", matching("^Bearer\\s[a-zA-Z0-9._-]+$"))
// Header 2: Exact tenant region match
.withHeader("X-Tenant-Region", equalTo("MH-PUNE-WEST"))
// Header 3: Negative assertion - Must NOT contain internal debug header
.withHeader("X-Internal-Debug", absent())
// Cookie: Must contain active session cookie
.withCookie("SESSION_ID", matching("^[a-f0-9]{32}$"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"profile\": \"AUTHENTICATED_SECURE\"}")));
// Execute matching call via REST Assured
given()
.spec(mockSpec)
.header("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.payload.sig")
.header("X-Tenant-Region", "MH-PUNE-WEST")
.cookie("SESSION_ID", "4f8a10c9bf124e89a0bc1123481029ba")
.when()
.get("/v1/secure/profile")
.then()
.statusCode(200)
.body("profile", equalTo("AUTHENTICATED_SECURE"));
System.out.println("[β] Header, cookie, and absent() predicates matched successfully.");
}
}
matchingJsonPath() to validate specific JSON attributes, evaluate array item counts, check numeric comparisons, and filter on nested child objects.
package com.nikita.restassured.wiremock.matching;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import io.restassured.http.ContentType;
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 JsonPathBodyMatchingTest extends WireMockBaseTest {
@Test(description = "Stub evaluating JSONPath predicates: nested fields, numeric filters, and array size")
public void testDeepJsonPathBodyMatching() {
stubFor(post(urlPathEqualTo("/v1/enrollment/batch"))
.withHeader("Content-Type", containing("application/json"))
// Predicate 1: Check root attribute
.withRequestBody(matchingJsonPath("$.academicYear", equalTo("2026")))
// Predicate 2: Check nested object attribute
.withRequestBody(matchingJsonPath("$.coordinator.department", equalTo("COMPUTER_SCIENCE")))
// Predicate 3: Filter expression checking that all courses have credits >= 3
.withRequestBody(matchingJsonPath("$.courses[?(@.credits >= 3)]"))
// Predicate 4: Verify array contains at least 2 courses
.withRequestBody(matchingJsonPath("$.courses.size()", matching("[2-9]|[1-9][0-9]+")))
.willReturn(aResponse()
.withStatus(201)
.withHeader("Content-Type", "application/json")
.withBody("{\"batchStatus\": \"PROCESSED\", \"totalEnrolled\": 2}")));
// Valid payload meeting all 4 JSONPath criteria
String requestPayload = "{\n" +
" \"academicYear\": \"2026\",\n" +
" \"coordinator\": {\n" +
" \"department\": \"COMPUTER_SCIENCE\"\n" +
" },\n" +
" \"courses\": [\n" +
" { \"code\": \"REST-201\", \"credits\": 4 },\n" +
" { \"code\": \"DOCKER-301\", \"credits\": 3 }\n" +
" ]\n" +
"}";
given()
.spec(mockSpec)
.body(requestPayload)
.when()
.post("/v1/enrollment/batch")
.then()
.statusCode(201)
.body("batchStatus", equalTo("PROCESSED"))
.body("totalEnrolled", equalTo(2));
System.out.println("[β] Complex JSONPath body predicates evaluated and satisfied.");
}
}
atPriority(). Creates a generic catch-all stub (priority 10) returning default data, alongside high-priority specific stubs (priority 1 and priority 2) returning custom edge-case responses for specific students.
package com.nikita.restassured.wiremock.matching;
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 PriorityCascadeTest extends WireMockBaseTest {
@BeforeClass
public void setupPriorityStubs() {
// =====================================================================
// STUB 1: LOWEST PRIORITY CATCH-ALL (Priority 10)
// Matches ANY student ID: /v1/students/.*
// =====================================================================
stubFor(get(urlPathMatching("/v1/students/.*"))
.atPriority(10) // Fallback lowest priority
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"profile\": \"DEFAULT_GENERIC_STUDENT\", \"tier\": \"STANDARD\"}")));
// =====================================================================
// STUB 2: MEDIUM PRIORITY SPECIFIC RECORD (Priority 5)
// Matches specific suspended student STU-SUSPENDED-99
// =====================================================================
stubFor(get(urlPathEqualTo("/v1/students/STU-SUSPENDED-99"))
.atPriority(5) // Overrides generic priority 10
.willReturn(aResponse()
.withStatus(403)
.withHeader("Content-Type", "application/json")
.withBody("{\"error\": \"ACCOUNT_SUSPENDED\", \"tier\": \"RESTRICTED\"}")));
// =====================================================================
// STUB 3: HIGHEST PRIORITY VIP RECORD (Priority 1)
// Matches VIP student STU-88219
// =====================================================================
stubFor(get(urlPathEqualTo("/v1/students/STU-88219"))
.atPriority(1) // Highest priority: Evaluated first!
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"profile\": \"VIP_HONORS_STUDENT\", \"tier\": \"PREMIUM\"}")));
System.out.println("[*] Priority stubs registered: Priority 1 (VIP), Priority 5 (Suspended), Priority 10 (Catch-All).");
}
@Test(description = "Verify VIP student STU-88219 triggers Priority 1 stub")
public void testVipStudentTriggersPriorityOne() {
given()
.spec(mockSpec)
.when()
.get("/v1/students/STU-88219")
.then()
.statusCode(200)
.body("profile", equalTo("VIP_HONORS_STUDENT"))
.body("tier", equalTo("PREMIUM"));
System.out.println("[β] Priority 1 stub selected over catch-all.");
}
@Test(description = "Verify suspended student STU-SUSPENDED-99 triggers Priority 5 stub")
public void testSuspendedStudentTriggersPriorityFive() {
given()
.spec(mockSpec)
.when()
.get("/v1/students/STU-SUSPENDED-99")
.then()
.statusCode(403)
.body("error", equalTo("ACCOUNT_SUSPENDED"));
System.out.println("[β] Priority 5 stub selected over catch-all.");
}
@Test(description = "Verify unmapped student STU-RANDOM-441 falls through to Priority 10 catch-all")
public void testRandomStudentTriggersCatchAll() {
given()
.spec(mockSpec)
.when()
.get("/v1/students/STU-RANDOM-441")
.then()
.statusCode(200)
.body("profile", equalTo("DEFAULT_GENERIC_STUDENT"))
.body("tier", equalTo("STANDARD"));
System.out.println("[β] Priority 10 catch-all stub selected for unmatched ID.");
}
}
matchingXPath() with namespace prefix declarations to inspect incoming XML request bodies and trigger stubs based on XPath node values and attribute criteria.
package com.nikita.restassured.wiremock.matching;
import com.nikita.restassured.wiremock.WireMockBaseTest;
import io.restassured.http.ContentType;
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 XmlXPathMatchingTest extends WireMockBaseTest {
@Test(description = "Stub matching incoming XML payload via namespaced XPath expression")
public void testXmlXPathBodyMatching() {
stubFor(post(urlPathEqualTo("/v1/academic/xml/enroll"))
.withHeader("Content-Type", containing("application/xml"))
// Evaluate XPath on namespaced XML document
.withRequestBody(matchingXPath("//acad:StudentEnrollment/acad:StudentId[text()='STU-88219']")
.withXPathNamespace("acad", "https://schemas.nikita-infotech.com/academic/v1"))
// Assert XML attribute on root element
.withRequestBody(matchingXPath("/acad:StudentEnrollment[@academicYear='2026']")
.withXPathNamespace("acad", "https://schemas.nikita-infotech.com/academic/v1"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/xml; charset=utf-8")
.withBody("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<EnrollmentAck xmlns=\"https://schemas.nikita-infotech.com/academic/v1\">\n" +
" <Status>CONFIRMED</Status>\n" +
" <StudentId>STU-88219</StudentId>\n" +
"</EnrollmentAck>")));
String xmlPayload = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<StudentEnrollment xmlns=\"https://schemas.nikita-infotech.com/academic/v1\" academicYear=\"2026\">\n" +
" <StudentId>STU-88219</StudentId>\n" +
" <FullName>Nikita Sharma</FullName>\n" +
"</StudentEnrollment>";
given()
.spec(mockSpec)
.contentType(ContentType.XML)
.body(xmlPayload)
.when()
.post("/v1/academic/xml/enroll")
.then()
.statusCode(200)
.contentType(ContentType.XML)
.body("EnrollmentAck.Status", equalTo("CONFIRMED"))
.body("EnrollmentAck.StudentId", equalTo("STU-88219"));
System.out.println("[β] Namespaced XPath body predicate matched XML payload successfully.");
}
}
X-Tenant-Id headers to return different mock datasets for Tenant Pune versus Tenant Mumbai, falling back to a default sandbox response.
package com.nikita.restassured.wiremock.matching;
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 MultiTenantRoutingTest extends WireMockBaseTest {
@BeforeClass
public void setupTenantStubs() {
// Priority 1: Tenant Pune explicit configuration
stubFor(get(urlPathEqualTo("/v1/tenant/configuration"))
.atPriority(1)
.withHeader("X-Tenant-Id", equalTo("TENANT_PUNE"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"region\": \"PUNE_WEST\", \"currency\": \"INR\", \"taxRate\": 0.18}")));
// Priority 2: Tenant Mumbai explicit configuration
stubFor(get(urlPathEqualTo("/v1/tenant/configuration"))
.atPriority(2)
.withHeader("X-Tenant-Id", equalTo("TENANT_MUMBAI"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"region\": \"MUMBAI_CENTRAL\", \"currency\": \"INR\", \"taxRate\": 0.18}")));
// Priority 10: Default Fallback for unspecified or sandbox tenants
stubFor(get(urlPathEqualTo("/v1/tenant/configuration"))
.atPriority(10)
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"region\": \"GLOBAL_SANDBOX\", \"currency\": \"USD\", \"taxRate\": 0.00}")));
}
@Test(description = "Verify Pune tenant header routes to Pune configuration stub")
public void testPuneTenantRouting() {
given()
.spec(mockSpec)
.header("X-Tenant-Id", "TENANT_PUNE")
.when()
.get("/v1/tenant/configuration")
.then()
.statusCode(200)
.body("region", equalTo("PUNE_WEST"))
.body("taxRate", equalTo(0.18f));
System.out.println("[β] Tenant Pune routed to priority 1 configuration.");
}
@Test(description = "Verify unmapped tenant header falls back to Sandbox stub")
public void testSandboxTenantFallback() {
given()
.spec(mockSpec)
.header("X-Tenant-Id", "UNKNOWN_TENANT_ID")
.when()
.get("/v1/tenant/configuration")
.then()
.statusCode(200)
.body("region", equalTo("GLOBAL_SANDBOX"))
.body("currency", equalTo("USD"));
System.out.println("[β] Unrecognized tenant routed to priority 10 fallback.");
}
}
inScenario(), whenScenarioStateIs(), willSetStateTo()) to simulate state transitions (e.g., initial GET returns empty, POST creates entity, subsequent GET returns populated entity).
package com.nikita.restassured.wiremock.matching;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.nikita.restassured.wiremock.WireMockBaseTest;
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;
import static org.hamcrest.Matchers.hasSize;
public class StatefulScenarioMatchingTest extends WireMockBaseTest {
private static final String ENROLLMENT_SCENARIO = "Student Enrollment Flow";
@Test(description = "Simulate stateful workflow: Initial GET empty β POST enlists student β Subsequent GET populated")
public void testStatefulScenarioTransitions() {
// STATE 1: Started - GET returns empty course roster
stubFor(get(urlPathEqualTo("/v1/students/STU-88219/courses"))
.inScenario(ENROLLMENT_SCENARIO)
.whenScenarioStateIs(Scenario.STARTED)
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"courses\": []}")));
// STATE TRANSITION: POST enlists student in course and transitions scenario state
stubFor(post(urlPathEqualTo("/v1/students/STU-88219/courses"))
.inScenario(ENROLLMENT_SCENARIO)
.whenScenarioStateIs(Scenario.STARTED)
.withRequestBody(matchingJsonPath("$.courseCode", equalTo("REST-201")))
.willSetStateTo("ENROLLED") // State changes to 'ENROLLED'
.willReturn(aResponse()
.withStatus(201)
.withHeader("Content-Type", "application/json")
.withBody("{\"status\": \"ENROLLED\", \"course\": \"REST-201\"}")));
// STATE 2: ENROLLED - Subsequent GET returns updated roster
stubFor(get(urlPathEqualTo("/v1/students/STU-88219/courses"))
.inScenario(ENROLLMENT_SCENARIO)
.whenScenarioStateIs("ENROLLED")
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"courses\": [{\"code\": \"REST-201\", \"credits\": 4}]}")));
// =============================================================
// EXECUTE STATEFUL REST ASSURED WORKFLOW
// =============================================================
// Call 1 (State: STARTED): Verify roster is empty
given().spec(mockSpec).get("/v1/students/STU-88219/courses")
.then().statusCode(200).body("courses", hasSize(0));
// Call 2 (Transition): Enroll in course
given().spec(mockSpec).body("{\"courseCode\": \"REST-201\"}").post("/v1/students/STU-88219/courses")
.then().statusCode(201).body("status", equalTo("ENROLLED"));
// Call 3 (State: ENROLLED): Verify roster contains enrolled course
given().spec(mockSpec).get("/v1/students/STU-88219/courses")
.then().statusCode(200).body("courses", hasSize(1))
.body("courses[0].code", equalTo("REST-201"));
System.out.println("[β] Stateful WireMock scenario transitioned cleanly across 3 sequential calls.");
}
}
urlMatching, fixing JSONPath syntax bugs, and inspecting WireMock's near-miss matching reports.
package com.nikita.restassured.wiremock.matching;
import com.github.tomakehurst.wiremock.verification.NearMiss;
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 MatchingAmbiguityTriageTest extends WireMockBaseTest {
// ==========================================================================
// PITFALL 1: PRIORITY INVERSION
// Symptom: A specific stub is registered, but WireMock returns the generic
// catch-all stub instead!
// CAUSE: The specific stub lacked atPriority(), so both stubs defaulted to
// priority 5, or the generic catch-all was registered with a LOWER number!
// FIX: Always assign explicit priority rankings: Specific=1, Catch-All=10!
// ==========================================================================
@Test(description = "Demonstrate diagnosing near-miss matching reports when requests fail to match stubs")
public void testDiagnoseNearMisses() {
// Stub expecting strict query param: "tier=GOLD"
stubFor(get(urlPathEqualTo("/v1/discounts"))
.withQueryParam("tier", equalTo("GOLD"))
.willReturn(aResponse().withStatus(200)));
// Request dispatched with minor typo: "tier=gold" (lowercase) causing 404:
given()
.spec(mockSpec)
.queryParam("tier", "gold") // Typo causes matching failure
.when()
.get("/v1/discounts")
.then()
.statusCode(404);
// Retrieve WireMock near-miss diagnostics to inspect closest matching stub
List<NearMiss> nearMisses = wireMockServer.findNearMissesForAllUnmatched();
Assert.assertFalse(nearMisses.isEmpty(), "WireMock must generate near-miss reports for debugging!");
NearMiss miss = nearMisses.get(0);
System.out.println("---------------- WIREMOCK NEAR-MISS REPORT ----------------");
System.out.println("URL Attempted : " + miss.getRequest().getUrl());
System.out.println("Closest Match : " + miss.getStubMapping().getRequest().getUrlPath());
System.out.println("Diff Reason : Query parameter 'tier' expected 'GOLD' but was 'gold'");
System.out.println("-----------------------------------------------------------");
}
}
WIREMOCK DYNAMIC MATCHING & PRIORITY SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β MATCHING CONSTRUCT β DSL SYNTAX EXAMPLE β PREDICATE TYPE β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Exact URL β urlEqualTo("/v1/path") β Exact String β Literal URL + Query match β
β Path Regex β urlPathMatching("/v1/.*") β Regex Path β Regex path, ignores query β
β Full URI Regex β urlMatching("/v1/.*\\?p=.*") β Regex URI β Regex across entire path+queryβ
β Query Parameter Match β withQueryParam("k", equalTo) β Parameter Filter β Explicit query param matching β
β Header Match β withHeader("Key", matching) β Header Filter β RegEx / Substring header checkβ
β Header Absence β withHeader("Key", absent()) β Negative Filter β Ensures header is NOT present β
β Cookie Match β withCookie("Name", equalTo) β Cookie Filter β Validates session cookies β
β JSONPath Match β matchingJsonPath("$.path") β Body Predicate β In-memory JSON tree query β
β XPath Match β matchingXPath("//tag/node") β Body Predicate β In-memory XML tree query β
β Priority Assignment β .atPriority(1) β Integer (1..10) β Lower integer = Higher rankingβ
β Scenario State Match β whenScenarioStateIs("STATE") β Stateful FSM β Conditional on scenario state β
β State Transition β willSetStateTo("NEXT_STATE") β Stateful FSM β Advances scenario state β
β Near-Miss Inspection β findNearMissesForAllUnmatchedβ Diagnostic Query β Reports closest stub diffs β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 DYNAMIC MATCHING & PRIORITY BEST PRACTICES: β
β 1. Always set explicit priorities: Use atPriority(1) for edge cases and atPriority(10) for catch-alls β
β 2. Prefer urlPathMatching over urlMatching: Isolate path matching from dynamic query parameters. β
β 3. Use matchingJsonPath for flexible payload checks: Avoid rigid string equality on JSON bodies. β
β 4. Leverage WireMock Scenarios for stateful flows: Model sequential workflows without real databases. β
β 5. Inspect Near-Miss reports on 404s: Pinpoint subtle case-sensitivity and parameter typos quickly. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ