π― 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.
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 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
match ==) and partial subset matching (match contains), showing how Karate handles missing attributes, extra server fields, and nested objects.
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 }
match each, validating order-independent lists via contains only, and verifying subsets using contains any.
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]'
'#(variable)' syntax. Enables parameterized validation without string concatenation.
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'
}
"""
_) in Karate fuzzy matchers to enforce custom validation rules, type checks, and format constraints.
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
match syntax as JSON. This example shows how to assert XML structures, read attributes via @attr, and evaluate XPath expressions.
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>
"""
karate.map(), karate.filter(), and type conversion helpers.
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']
type discriminator.
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
karate.call().
# ==============================================================================
# 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 }
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. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ