KARATE FEATURE FILES & ADVANCED PAYLOAD ASSERTIONS

Architect high-precision contract assertions in Karate: Exact match vs. partial contains, array matching expressions (match each, contains only, contains any), embedded expressions (#(var)), schema macros, JSON/XML conversion bridges, and conditional assertion logic.

🎯 Declarative Assertion Power Without Procedural Code

In enterprise API automation, validating large, nested payloads with traditional procedural loops and multiple assert statements results in brittle, unreadable test suites. Karate Feature Files offer a unified, declarative assertion engine where entire JSON and XML documents can be evaluated with a single match statement. By understanding the distinction between strict equality (match ==), partial validation (match contains), and order-independent array assertions (match each, contains only, contains any), test engineers can validate contracts with precision. With embedded expressions ('#(variable)'), fuzzy schema macros, and custom JavaScript predicates (#? _ > 0), Karate provides a powerful, concise syntax for validating enterprise microservice responses.

1. Karate Assertion Topography & Match Operators Grammar
A comprehensive mapping of Karate's assertion operators, demonstrating deep object comparison, subset validation, negation, and collection modifiers side by side.
Karate Match Grammar & Comparison Operators
KARATE MATCH OPERATORS TAXONOMY:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ MATCH OPERATOR      β”‚ SYNTAX PATTERN               β”‚ SEMANTIC BEHAVIOR & VALIDATION MANDATE                 β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ match ==            β”‚ match response == expected   β”‚ Strict deep equality; keys and array order must match  β”‚
β”‚ match !=            β”‚ match response != unexpected β”‚ Deep inequality; fails if objects are identical        β”‚
β”‚ match contains      β”‚ match response contains {k:v}β”‚ Sub-set match; asserts specified keys exist in object  β”‚
β”‚ match !contains     β”‚ match response !contains {..}β”‚ Asserts target keys or elements do NOT exist           β”‚
β”‚ match contains only β”‚ match arr contains only [..] β”‚ Asserts exact elements exist; order is ignored         β”‚
β”‚ match contains any  β”‚ match arr contains any [..]  β”‚ Asserts AT LEAST ONE of the target items exists        β”‚
β”‚ match each ==       β”‚ match each arr == { status } β”‚ Iterates every array element, asserting target contractβ”‚
β”‚ match header        β”‚ match header X-ID == '#uuid' β”‚ Asserts HTTP response header values and formats        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

EVALUATION PIPELINE BEHAVIOR:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ [ Server JSON Response ] ──► [ Parser Engine ] ──► [ Match Evaluator ] ──► [ Result: PASS / FAIL ]    β”‚
β”‚  {"id":"STU-101",             Auto-identifies      Evaluates keys,         If mismatch: prints        β”‚
β”‚   "credits":4,                data types           fuzzy markers, and      deep visual JSON diff      β”‚
β”‚   "status":"ACTIVE"}          (JSON / XML)         embedded expressions    highlighting exact delta   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: Use 'match ==' when validating strict contractual boundaries where undeclared keys or missing fields constitute a breaking change. Use 'match contains' for integration sanity tests where backend additions should not break the test suite.
Real-Time Example 1: Deep Object Equality vs. Partial Subset Matching
Comparing strict equality (match ==) and partial subset matching (match contains), showing how Karate handles missing attributes, extra server fields, and nested objects.
Gherkin Feature (deep_equality_vs_contains.feature)
Feature: Deep Object Matching and Partial Contains Validation

  Background:
    * url baseUrl
    * def sampleStudent =
      """
      {
        "studentId": "STU-88219",
        "name": "Nikita Sharma",
        "academics": {
          "gpa": 3.92,
          "credits": 64,
          "major": "Computer Science"
        },
        "tags": ["honor-roll", "api-lead"]
      }
      """

  Scenario: Evaluate strict deep equality against entire object tree
    # Strict matching: Key order does not matter in JSON objects, but all keys must exist
    * match sampleStudent == 
      """
      {
        "studentId": "STU-88219",
        "name": "Nikita Sharma",
        "academics": {
          "gpa": 3.92,
          "credits": 64,
          "major": "Computer Science"
        },
        "tags": ["honor-roll", "api-lead"]
      }
      """

  Scenario: Evaluate partial subset matching via contains
    # Asserts specific root keys while ignoring 'academics' and 'tags'
    * match sampleStudent contains { studentId: 'STU-88219', name: 'Nikita Sharma' }

    # Deep partial contains on nested sub-object
    * match sampleStudent.academics contains { major: 'Computer Science' }

    # Negation: Asserting an unapproved field does NOT exist
    * match sampleStudent !contains { isSuspended: true }
Console Visual Diff Output (on failure): match failed: EQUALS $ | not equal | actual has 1 more key than expected: 'tags' (MAP:MAP) {"studentId":"STU-88219","name":"Nikita Sharma","academics":{...},"tags":["honor-roll"]} {"studentId":"STU-88219","name":"Nikita Sharma","academics":{...}}
Real-Time Example 2: Advanced Array Matching (match each, contains only, any)
Validating complex arrays and collections: applying schema contracts across every array element using match each, validating order-independent lists via contains only, and verifying subsets using contains any.
Gherkin Feature (advanced_array_matching.feature)
Feature: Complex Array Assertions and Collection Matchers

  Background:
    * def coursesList =
      """
      [
        { "code": "API-101", "credits": 4, "active": true, "instructor": "Nikita" },
        { "code": "PY-202",  "credits": 3, "active": true, "instructor": "Aarav" },
        { "code": "SEC-303", "credits": 5, "active": true, "instructor": "Rohan" }
      ]
      """

  Scenario: Assert every element in collection matches a strict schema contract
    # match each iterates through every element in the array
    * match each coursesList == 
      """
      {
        "code": '#regex ^[A-Z]{2,3}-[0-9]{3}$',
        "credits": '#number? _ >= 1 && _ <= 6',
        "active": true,
        "instructor": '#string'
      }
      """

  Scenario: Assert order-independent collection presence
    * def courseCodes = $coursesList[*].code

    # 1. contains only: Exact elements must exist; order is completely ignored
    * match courseCodes contains only ['PY-202', 'API-101', 'SEC-303']

    # 2. contains any: AT LEAST ONE element must match
    * match courseCodes contains any ['INVALID-CODE', 'API-101', 'UNKNOWN-999']

    # 3. Array length assertion
    * match coursesList == '#[3]'

    # 4. Filtered condition assertion on collection length:
    # Asserts that all courses with credits >= 4 count exactly 2
    * def highCreditCourses = $coursesList[?(@.credits >= 4)]
    * match highCreditCourses == '#[2]'
JSONPath Integration: Karate seamlessly combines JSONPath expressions ($coursesList[*].code) with matchers. The expression $coursesList[?(@.credits >= 4)] filters the array in place, and '#[2]' asserts that the resulting subset contains exactly two elements.
Real-Time Example 3: Dynamic Embedded Expressions ('#(variable)')
Injecting dynamic variables into payload requests and assertion templates using Karate's '#(variable)' syntax. Enables parameterized validation without string concatenation.
Gherkin Feature (embedded_expressions.feature)
Feature: Dynamic Payload Injection and Embedded Expression Matching

  Background:
    * url baseUrl
    * def dynamicBatchId = 'BTCH-' + java.util.UUID.randomUUID().toString().substring(0, 8)
    * def expectedCredits = 4
    * def targetTrack = 'API-AUTOMATION-PRO'

  Scenario: Inject runtime variables into payload and assert dynamic response
    Given path 'batches'
    # Embedded expressions evaluate variables inside multi-line JSON blocks
    And request
      """
      {
        "batchIdentifier": '#(dynamicBatchId)',
        "allocatedCredits": '#(expectedCredits)',
        "courseTrack": '#(targetTrack)',
        "metadata": {
          "initiatedAt": '#(java.lang.System.currentTimeMillis())'
        }
      }
      """
    When method post
    Then status 201

    # Assert dynamic response echoes back the injected runtime values
    And match response ==
      """
      {
        "id": '#string',
        "batchIdentifier": '#(dynamicBatchId)',
        "allocatedCredits": '#(expectedCredits)',
        "courseTrack": '#(targetTrack)',
        "status": "PROVISIONED",
        "createdAt": '#number'
      }
      """
Execution Output: >> POST https://api.nikita-infotech.com/v1/batches >> Body: {"batchIdentifier":"BTCH-a1b2c3d4","allocatedCredits":4,"courseTrack":"API-AUTOMATION-PRO"...} << HTTP/1.1 201 Created << Body: {"id":"REC-99120","batchIdentifier":"BTCH-a1b2c3d4","allocatedCredits":4...} match response.batchIdentifier == dynamicBatchId -> PASSED
Real-Time Example 4: Complex Schema Macros with Self-Evaluating Predicates (#?)
Building complex schema macros using the self-evaluating underscore operator (_) in Karate fuzzy matchers to enforce custom validation rules, type checks, and format constraints.
Gherkin Feature (schema_macros_predicates.feature)
Feature: Advanced Schema Validation via Self-Evaluating Predicates

  Background:
    # 1. Custom JavaScript Predicate Functions declared in Background
    * def isValidEmail = function(val){ return val.indexOf('@nikita-infotech.com') !== -1 }
    * def isPositiveNonZero = function(val){ return val > 0 }
    * def isIsoTimestamp = 
      """
      function(val) {
        var pattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;
        return pattern.test(val);
      }
      """

    # 2. Schema Definition incorporating self-evaluating predicates (#?)
    * def studentMasterContract =
      """
      {
        "studentId": '#regex ^STU-[0-9]{5}$',
        "email": '#? isValidEmail(_)',
        "credits": '#number? isPositiveNonZero(_)',
        "gpa": '#number? _ >= 0.0 && _ <= 4.0',
        "registeredAt": '#? isIsoTimestamp(_)',
        "accountState": '#? _ == "ACTIVE" || _ == "PENDING"',
        "profile": {
          "bio": '##string',
          "website": '##regex ^https?://.*'
        }
      }
      """

  Scenario: Validate incoming server payload against the master schema macro
    * def serverPayload =
      """
      {
        "studentId": "STU-88219",
        "email": "nikita.sharma@nikita-infotech.com",
        "credits": 4,
        "gpa": 3.85,
        "registeredAt": "2026-11-01T09:30:00Z",
        "accountState": "ACTIVE",
        "profile": {
          "bio": "API Quality Architect",
          "website": "https://nikita-infotech.com"
        }
      }
      """

    # Single-line validation of entire complex payload
    * match serverPayload == studentMasterContract
Predicate Operator Power: The '#? fn(_)' syntax passes the actual value of the field into the JavaScript function represented by the underscore (_). If the function returns true, the assertion passes; if false, it reports a validation failure.
Real-Time Example 6: XML Payload Assertions & XPath Evaluation in Karate
Karate natively parses XML documents using the same match syntax as JSON. This example shows how to assert XML structures, read attributes via @attr, and evaluate XPath expressions.
Gherkin Feature (xml_payload_assertions.feature)
Feature: XML Document Traversal and XPath Assertions in Karate

  Background:
    * def sampleXml =
      """
      <StudentRegistry campus="Pune">
          <Student id="STU-88219" active="true">
              <Name>Nikita Sharma</Name>
              <GPA>3.95</GPA>
              <Courses>
                  <Course code="API-101" credits="4"/>
                  <Course code="PY-202" credits="3"/>
              </Courses>
          </Student>
      </StudentRegistry>
      """

  Scenario: Assert XML attributes, elements, and XPath expressions natively
    # 1. Assert Root XML Attribute using @ syntax
    * match sampleXml/StudentRegistry/@campus == 'Pune'

    # 2. Assert Child Element Text Content
    * match sampleXml/StudentRegistry/Student/Name == 'Nikita Sharma'

    # 3. XPath Attribute Selection & Boolean Match
    * match sampleXml //Student/@active == 'true'

    # 4. Match XML element using Fuzzy Matchers
    * match sampleXml //Student/GPA == '#number? _ > 3.0'

    # 5. Extract multiple XML attributes into an array and assert values
    * def courseCodes = $sampleXml/StudentRegistry/Student/Courses/Course/@code
    * match courseCodes == ['API-101', 'PY-202']

    # 6. Deep XML Structure Match:
    * match sampleXml/StudentRegistry/Student == 
      """
      <Student id="STU-88219" active="true">
          <Name>Nikita Sharma</Name>
          <GPA>#number</GPA>
          <Courses>
              <Course code="API-101" credits="4"/>
              <Course code="PY-202" credits="3"/>
          </Courses>
      </Student>
      """
XML Convenience: In Karate, XML is a first-class citizen. You do not need an external XML parser or XPath library; expressions like sampleXml/StudentRegistry/@campus work natively inside feature files.
Real-Time Example 7: Data Transformation & Type Casting in Karate (karate.map)
Manipulating response collections before assertion using Karate's built-in JavaScript transformation utilities: karate.map(), karate.filter(), and type conversion helpers.
Gherkin Feature (data_transformation_helpers.feature)
Feature: Functional Data Transformation and Mapping Utilities

  Scenario: Transform raw API array into normalized test dataset
    * def rawApiStudents =
      """
      [
        { "id": 101, "first_name": "Nikita", "last_name": "Sharma", "score": "95" },
        { "id": 102, "first_name": "Aarav",  "last_name": "Verma",  "score": "88" },
        { "id": 103, "first_name": "Rohan",  "last_name": "Patil",  "score": "74" }
      ]
      """

    # 1. karate.map(): Transform objects (assemble full name and cast score to integer)
    * def mapper = function(x){ return { studentId: 'STU-' + x.id, fullName: x.first_name + ' ' + x.last_name, marks: parseInt(x.score) } }
    * def normalizedList = karate.map(rawApiStudents, mapper)

    # Assert transformed list structure
    * match normalizedList[0] == { studentId: 'STU-101', fullName: 'Nikita Sharma', marks: 95 }
    * match normalizedList[1] == { studentId: 'STU-102', fullName: 'Aarav Verma', marks: 88 }

    # 2. karate.filter(): Select only students with marks >= 85
    * def filterPredicate = function(x){ return x.marks >= 85 }
    * def honorsList = karate.filter(normalizedList, filterPredicate)

    * match honorsList == '#[2]'
    * match honorsList[*].fullName contains only ['Nikita Sharma', 'Aarav Verma']
Transformative Power: karate.map() and karate.filter() allow you to sanitize and normalize server responses directly in Gherkin feature files before running assertions, eliminating the need for external helper scripts.
Real-Time Example 8: Handling Dynamic Keys & Polymorphic Payloads
Validating responses where object keys are dynamic (e.g. UUIDs or dates as map keys) or where payloads are polymorphic, changing structure based on a type discriminator.
Gherkin Feature (dynamic_keys_polymorphic.feature)
Feature: Dynamic Map Keys and Polymorphic Response Validation

  Scenario: Validate dynamic UUID map keys using karate.keysOf()
    # Server returns a dictionary where keys are dynamic UUIDs:
    * def dynamicResponse =
      """
      {
        "9f8a10c9-bf12": { "module": "API-101", "completed": true },
        "3b1a20d4-cf34": { "module": "PY-202",  "completed": false }
      }
      """

    # 1. Extract all dynamic keys from the map:
    * def keys = karate.keysOf(dynamicResponse)
    * match keys == '#[2] #regex ^[a-f0-9]{8}-[a-f0-9]{4}$'

    # 2. Validate every value object across dynamic keys:
    * def values = karate.valuesOf(dynamicResponse)
    * match each values == { module: '#string', completed: '#boolean' }

  Scenario: Validate polymorphic payload structure based on discriminator
    * def paymentResponse = { "method": "UPI", "upiId": "nikita@upi", "amount": 14999.00 }

    # Conditional assertion using JavaScript ternary logic:
    * def upiSchema = { "method": "UPI", "upiId": '#regex ^.+@.+$', "amount": '#number' }
    * def cardSchema = { "method": "CARD", "cardLast4": '#regex ^[0-9]{4}$', "amount": '#number' }

    * def expectedSchema = paymentResponse.method == 'UPI' ? upiSchema : cardSchema
    * match paymentResponse == expectedSchema
Polymorphic Flexibility: Combining karate.keysOf() and ternary schema selection allows Karate to validate dynamic map keys and polymorphic payloads cleanly without complex conditional branching.
Real-Time Example 9: Reusable Assertion Helpers in External Feature Files
Abstracting repetitive assertion logic (e.g. verifying standard RFC 7807 problem detail errors or checking multi-header security baselines) into reusable helper features invoked via karate.call().
Gherkin Feature (Reusable Contract Assertions)
# ==============================================================================
# REUSABLE ASSERTION HELPER: src/test/java/helpers/assert_rfc7807_error.feature
# ==============================================================================
@ignore
Feature: Reusable RFC 7807 Error Contract Validator

  Scenario: Validate error response structure
    # Expects caller to pass 'targetResponse' and 'expectedStatus'
    * match targetResponse ==
      """
      {
        "type": '#string',
        "title": '#string',
        "status": '#(expectedStatus)',
        "detail": '#string',
        "instance": '#? _.startsWith("/")'
      }
      """

# ==============================================================================
# MAIN TEST FEATURE FILE: src/test/java/features/negative_tests.feature
# ==============================================================================
Feature: Negative API Validation using Reusable Assertion Helpers

  Background:
    * url baseUrl

  Scenario: Verify 404 Not Found returns compliant RFC 7807 error envelope
    Given path 'students', 'STU-NONEXISTENT'
    When method get
    Then status 404

    # Invoke reusable assertion helper, passing the response and expected status
    * call read('classpath:helpers/assert_rfc7807_error.feature') { targetResponse: response, expectedStatus: 404 }
Reusability Benefit: Centralizing common assertions in helper features keeps tests DRY. If the standard error envelope updates (e.g. adding an errorTraceId field), updating the helper validates the change across all negative scenarios.
Real-Time Example 10: Karate Matchers & Assertion Reference Matrix
A comprehensive reference summary pairing Karate match expressions, fuzzy markers, collection operations, and best practices for test automation engineers.
Karate Matchers & Assertion Quick Reference Matrix
KARATE MATCHERS & ASSERTIONS QUICK REFERENCE:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ OPERATOR / MARKER   β”‚ SYNTAX EXAMPLE               β”‚ PRIMARY PURPOSE & BEHAVIOR                       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ match ==            β”‚ match res == { id: 10 }      β”‚ Strict deep equality (all keys must match)       β”‚
β”‚ match contains      β”‚ match res contains { id: 10 }β”‚ Partial matching (checks for declared keys only) β”‚
β”‚ match contains only β”‚ match arr contains only [..] β”‚ Order-independent exact array content match      β”‚
β”‚ match contains any  β”‚ match arr contains any [..]  β”‚ Asserts at least one element exists in array     β”‚
β”‚ match each          β”‚ match each arr == { id: '#numβ”‚ Evaluates contract against every array element   β”‚
β”‚ #string / #number   β”‚ "id": "#string", "gpa": "#numβ”‚ Fuzzy matcher verifying primitive data types     β”‚
β”‚ ##string / ##number β”‚ "phone": "##string"          β”‚ Optional matcher (permits null, missing, or type)β”‚
β”‚ #array / #object    β”‚ "tags": "#array"             β”‚ Verifies JSON array or object composite types    β”‚
β”‚ #regex <pattern>    β”‚ "id": "#regex ^STU-[0-9]{5}$"β”‚ Validates value matches regular expression       β”‚
β”‚ #? <js-expression>  β”‚ "age": "#? _ >= 18 && _ <= 65β”‚ Self-evaluating JS expression constraint on fieldβ”‚
β”‚ '#(variable)'       β”‚ "name": '#(studentName)'     β”‚ Injects dynamic runtime variable into match/body β”‚
β”‚ karate.keysOf(obj)  β”‚ def keys = karate.keysOf(res)β”‚ Extracts list of map keys for dynamic validation β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ TOP 5 KARATE ASSERTION BEST PRACTICES:                                                                β”‚
β”‚ 1. Match full schemas: Define reusable schema objects and validate using a single match == statement. β”‚
β”‚ 2. Use double-hash for optionals: Use ##string for nullable or conditionally returned fields.         β”‚
β”‚ 3. Use contains only for unordered lists: Prevents test flakiness caused by server-side sorting.      β”‚
β”‚ 4. Leverage self-evaluating predicates (#?): Write inline business logic rules without Java helpers.  β”‚
β”‚ 5. Encapsulate common error checks: Abstract standard 4xx/5xx error assertions into helper features.  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Make full use of Karate's declarative assertion engine. Combining fuzzy matchers, self-evaluating predicates, and JSONPath queries in your feature files provides thorough contract validation without writing verbose procedural assertions.