π§ Deterministic Cloud Routing & Explicit Response Steering
While Postman Mock Servers provide an automatic heuristic matching algorithm to select saved Examples based on URL paths and query parameters, automated testing frameworks often require absolute deterministic control. When testing negative scenarios, timeout boundaries, or edge cases, depending on path scoring alone can lead to fragile testsβespecially when multiple response examples share the same URL endpoint. Postman addresses this through its dedicated x-mock-* control headers. By attaching custom request headers like x-mock-response-code, x-mock-response-name, x-mock-response-id, and x-mock-match-request-body, test engineers can override default scoring, steer cloud routers to return specific status codes, enforce payload body hash matching, and bypass intermediary edge caches on demand.
x-mock-* headers before running heuristic scoring, short-circuiting standard resolution paths.
POSTMAN CLOUD ROUTER CONTROL HEADER EVALUATION ORDER:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β INCOMING CLIENT REQUEST: Target https://<mock-id>.mock.pstmn.io/v1/students β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FAST PATH 1: EXACT UNIQUE IDENTIFIER OVERRIDE (Highest Absolute Precedence) β
β Header: x-mock-response-id: <example_uuid> β
β βββ FOUND: Returns the exact example linked to the UUID immediately β
β βββ NOT FOUND: Falls back to next evaluation rule β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FAST PATH 2: EXACT EXAMPLE NAME OVERRIDE β
β Header: x-mock-response-name: "422 Validation Error" β
β βββ FOUND: Returns the example with the exact matching Title text string β
β βββ NOT FOUND: Falls back to next evaluation rule β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β FAST PATH 3: STATUS CODE POOL FILTERING β
β Header: x-mock-response-code: 404 β
β βββ Filters candidate example pool strictly to items where example.status == 404 β
β βββ Runs path and query heuristic scoring only on the filtered status subset β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ADVANCED MATCHING INSTRUCTIONS β
β - x-mock-match-request-body: true βββΊ Compares inbound JSON body hash against example β
β - x-mock-match-request-headers: HeaderA βββΊ Enforces strict equality on declared headers β
β - x-mock-cache-bypass: true βββΊ Forces router to re-read workspace state β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ==============================================================================
// PRE-REQUEST SCRIPT: Programmatic Status Code Steering
// Request: GET {{baseUrl}}/v1/students/:studentId
// ==============================================================================
// Read desired scenario from local variables or data file
const targetStatus = pm.variables.get("targetStatus") || "404";
// Inject x-mock-response-code header onto the outbound request
pm.request.headers.upsert({
key: "x-mock-response-code",
value: targetStatus
});
console.log(`[+] Injected 'x-mock-response-code: ${targetStatus}' for mock steering.`);
// ==============================================================================
// TESTS TAB: Validating Directed Response Status
// ==============================================================================
pm.test(`[MOCK STEERING] Router respected control header and returned ${targetStatus}`, function () {
pm.response.to.have.status(Number(targetStatus));
if (targetStatus === "404") {
const res = pm.response.json();
pm.expect(res.error).to.eql("STUDENT_NOT_FOUND");
}
});
// ==============================================================================
// PRE-REQUEST SCRIPT: Example Selection by Exact Title
// Endpoint: POST {{baseUrl}}/v1/enrollments
// ==============================================================================
// Target Example Title saved in Postman Collection under this request:
// "422 Unprocessable - Missing Prerequisite Courses"
const selectedExampleName = "422 Unprocessable - Missing Prerequisite Courses";
pm.request.headers.upsert({
key: "x-mock-response-name",
value: selectedExampleName
});
console.log(`[*] Target Mock Example Title: "${selectedExampleName}"`);
// ==============================================================================
// TESTS TAB: Contract Verification of Selected Example
// ==============================================================================
pm.test("[NAMED EXAMPLE] Received exact named error payload variant", function () {
pm.response.to.have.status(422);
const body = pm.response.json();
pm.expect(body.errorCode).to.eql("PREREQUISITE_COURSE_REQUIRED");
pm.expect(body.missingPrerequisites).to.be.an("array").that.includes("API-101");
});
// ==============================================================================
// PRE-REQUEST SCRIPT: Direct UUID Example Steering
// (Example UUID can be found in the Postman URL: /example/<uuid>)
// ==============================================================================
const canonicalExampleId = "8f9b10c9-bf12-4e89-a0bc-1123481029ba";
pm.request.headers.upsert({
key: "x-mock-response-id",
value: canonicalExampleId
});
console.log(`[+] Enforced strict example UUID pointer: ${canonicalExampleId}`);
// ==============================================================================
// TESTS TAB: Validating Pinned Example Contract
// ==============================================================================
pm.test("[UUID ROUTING] Pinned example returned without ambiguity", function () {
pm.response.to.have.status(200);
const res = pm.response.json();
pm.expect(res.data.recordType).to.eql("CANONICAL_PINNED_TEST_CASE");
});
x-mock-match-request-body: true instructs the router to hash the incoming body and match it against saved examples.
// ==============================================================================
// PRE-REQUEST SCRIPT: Enabling Body Matching on Mutating Endpoints
// Endpoint: POST {{baseUrl}}/v1/students
// ==============================================================================
// 1. Instruct the Postman Cloud router to evaluate the raw request body
pm.request.headers.upsert({
key: "x-mock-match-request-body",
value: "true"
});
// 2. Set the outbound payload body
const payload = {
fullName: "Nikita Sharma",
email: "nikita.sharma@nikita-infotech.com",
academicTrack: "ENTERPRISE_AUTOMATION"
};
pm.request.body.update(JSON.stringify(payload));
console.log("[+] x-mock-match-request-body enabled for payload matching.");
// ==============================================================================
// TESTS TAB: Validating Body-Matched Example
// ==============================================================================
pm.test("[BODY MATCH] Cloud router matched body hash and returned 201 Created", function () {
pm.response.to.have.status(201);
const data = pm.response.json().data;
pm.expect(data.email).to.eql("nikita.sharma@nikita-infotech.com");
});
X-Tenant-Context or Accept) during candidate scoring.
// ==============================================================================
// PRE-REQUEST SCRIPT: Selective Header-Based Mock Routing
// ==============================================================================
// Instruct router which specific headers to evaluate during matching
pm.request.headers.upsert({
key: "x-mock-match-request-headers",
value: "X-Tenant-Context, X-Client-Tier"
});
// Provide the specific header values to match
pm.request.headers.upsert({
key: "X-Tenant-Context",
value: "MAHARASHTRA_WEST_01"
});
pm.request.headers.upsert({
key: "X-Client-Tier",
value: "ENTERPRISE_PREMIUM"
});
console.log("[+] Configured selective header matching for Tenant and Tier.");
// ==============================================================================
// TESTS TAB: Validating Tenant-Matched Mock Response
// ==============================================================================
pm.test("[HEADER MATCH] Returned mock response corresponding to Enterprise Tenant", function () {
pm.response.to.have.status(200);
const body = pm.response.json();
pm.expect(body.tier).to.eql("ENTERPRISE_PREMIUM");
pm.expect(body.region).to.eql("MAHARASHTRA_WEST_01");
});
x-mock-cache-bypass: true guarantees requests fetch the latest edits immediately.
// ==============================================================================
// PRE-REQUEST SCRIPT: Edge Cache Bypass Directive
// Attach to collections or requests under active development
// ==============================================================================
// Force Postman edge nodes to bypass cached example representations
pm.request.headers.upsert({
key: "x-mock-cache-bypass",
value: "true"
});
console.log("[+] Cache bypass active: Fresh example evaluation enforced.");
// ==============================================================================
// TESTS TAB: Auditing Response Freshness
// ==============================================================================
pm.test("[CACHE AUDIT] Response evaluated fresh from collection state", function () {
pm.response.to.have.status(200);
// Postman returns cache telemetry in response headers
if (pm.response.headers.has("x-cache")) {
console.log(`[*] Edge Cache Telemetry: ${pm.response.headers.get("x-cache")}`);
}
});
x-mock-response-code to validate error handling without modifying collection endpoints.
// ==============================================================================
// PRE-REQUEST SCRIPT: Data-Driven Status Injection
// Consumes rows from negative_scenarios.csv (columns: scenarioId, expectedStatus)
// ==============================================================================
const desiredCode = pm.iterationData.get("expectedStatus") || "200";
const scenarioId = pm.iterationData.get("scenarioId") || "MANUAL_RUN";
pm.request.headers.upsert({
key: "x-mock-response-code",
value: desiredCode.toString()
});
console.log(`[*] Scenario [${scenarioId}]: Steering mock to return HTTP ${desiredCode}`);
// ==============================================================================
// TESTS TAB: Validating Error Handling Across Injected Status Codes
// ==============================================================================
pm.test(`[${scenarioId}] Client application handled HTTP ${desiredCode} gracefully`, function () {
pm.response.to.have.status(Number(desiredCode));
if (Number(desiredCode) >= 400) {
pm.expect(pm.response.is.error).to.be.true;
pm.expect(pm.response.json()).to.have.property("error");
}
});
x-mock-response-code specifies a status code that does not exist in any saved example for that endpoint.
// ==============================================================================
// TESTS TAB: Diagnostic Handler for Mock Control Header Failures
// ==============================================================================
if (pm.response.code === 404 && pm.response.text().includes("No matching example found")) {
const requestedCode = pm.request.headers.get("x-mock-response-code");
const requestedName = pm.request.headers.get("x-mock-response-name");
const requestedId = pm.request.headers.get("x-mock-response-id");
console.error("====== MOCK CONTROL DIRECTIVE MISMATCH ======");
console.error(` Method & Path : ${pm.request.method} ${pm.request.url.getPath()}`);
console.error(` x-mock-response-code : ${requestedCode || '(not set)'}`);
console.error(` x-mock-response-name : ${requestedName || '(not set)'}`);
console.error(` x-mock-response-id : ${requestedId || '(not set)'}`);
console.error("=============================================");
pm.test("[MOCK ERROR] Diagnose matching failure reason", function () {
pm.expect.fail(`Mock matching failed! Check that an Example exists under '${pm.request.method} ${pm.request.url.getPath()}' with matching criteria.`);
});
} else {
pm.test("[MOCK SUCCESS] Request matched and returned expected example", function () {
pm.expect(pm.response.code).to.be.below(500);
});
}
x-mock-* control header, valid values, precedence levels, and operational best practices for QA automation architects.
X-MOCK-* CONTROL HEADERS SPECIFICATION MATRIX:
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β HEADER NAME β EXAMPLE VALUE β PRECEDENCE TIER β PRIMARY OPERATIONAL EFFECT β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β x-mock-response-id β <example_uuid> β 1 (Absolute Top) β Returns example by UUID β
β x-mock-response-name β "422 Validation Error" β 2 (Override) β Returns example by Title β
β x-mock-response-code β 200, 201, 404, 500 β 3 (Status Filter)β Filters to status code β
β x-mock-match-request-body β "true" β 4 (Hash Match) β Matches JSON payload hash β
β x-mock-match-request-headers β "X-Tenant, Accept" β 5 (Header Match) β Matches declared headers β
β x-mock-cache-bypass β "true" β Control β Forces fresh evaluation β
β x-api-key β PMAK-<token> β Security β Authenticates Private Mocks β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 MOCK CONTROL HEADER BEST PRACTICES: β
β 1. Steer negative tests with x-mock-response-code: Force 4xx/5xx status codes without changing URLs. β
β 2. Use x-mock-match-request-body for POST endpoints: Differentiate responses based on JSON payloads. β
β 3. Enable x-mock-cache-bypass during development: Ensure example edits take effect immediately. β
β 4. Name examples descriptively for x-mock-response-name: Enables clear, self-documenting test code. β
β 5. Audit 404 errors carefully: Verify that an example with the specified status or name actually exists. β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ