×
☰ See All Chapters

Karate Testing REST Service Response

 ‘$' represents the response. $ always refers to the JSON 'root', This can be used to frame a JSON Path and can be compared with the expected output using match operator.

JSONPath

Description

$

the root object/element

@

the current object/element

. or []

child operator

..

recursive descent. JSONPath borrows this syntax from E4X.

*

wildcard. All objects/elements regardless their names.

[]

subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator.

[,]

Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set.

[start:end:step]

array slice operator borrowed from ES4.

?()

applies a filter (script) expression.

()

script expression, using the underlying script engine.

Fuzzy Matching

In the case where we don't know the exact value that is returned, we can still validate the value using markers — placeholders for matching fields in the response.

The supported markers are the following:

Marker

Description

#ignore

Skip comparison for this field even if the data element or JSON key is present

#null

Expects actual value to be null, and the data element or JSON key must be present

#notnull

Expects actual value to be not-null

#present

Actual value can be any type or even null, but the key must be present (only for JSON / XML, see below)

#notpresent

Expects the key to be not present at all (only for JSON / XML, see below)

#array

Expects actual value to be a JSON array

#object

Expects actual value to be a JSON object

#boolean

Expects actual value to be a boolean true or false

#number

Expects actual value to be a number

#string

Expects actual value to be a string

#uuid

Expects actual (string) value to conform to the UUID format

#regex STR

Expects actual (string) value to match the regular-expression 'STR' (see examples above)

#? EXPR

Expects the JavaScript expression 'EXPR' to evaluate to true, see self-validation expressionsbelow

#[NUM] EXPR

Advanced array validation, see schema validation

#(EXPR)

For completeness, embedded expressions belong in this list as well

 

Note that #present and #notpresent only make sense when you are matching within a JSON or XML context or using a JsonPath or XPath on the left-hand-side.

def json = { foo: 'bar' }

match json == { foo: '#present' }

match json.nope == '#notpresent'

The rest can also be used even in 'primitive' data matches like so:

match foo == '#string'

# convenient (and recommended) way to check for array length

match bar == '#[2]'

Optional Fields

If two cross-hatch # symbols are used as the prefix (for example: ##number), it means that the key is optional or that the value can be null.

def foo = { bar: 'baz' }

match foo == { bar: '#string', ban: '##string' }

 


All Chapters
Author