In a nutshell
Assertions are the validation layer in API testing, determining whether the data returned in a response meets the expected outcome. You specify which part of the response to evaluate by selecting a source such as Header, Status Code, JSON Body, or XML Body, then define the expected value and an operator to perform the comparison. Multiple assertions can be added to a single test case to validate different aspects of the same API response.
Overview
Assertions are used to validate a response. If the assertions are not satisfied, the test fails.
Assertions can be applied using:
Source: Location from where the values will be compared. You can select Header, Status code, XML body, or JSON body as the source.
The following is a sample JSON key-value response:
{
"id":1,
"name":"Leanne Graham",
"username":"Bret",
"address":{
"city":"Gwenborough",
"geo":{
"lat":"-37.3159",
"lng":"81.1496"
}
},
"phoneNumbers":[
{
"type":"home",
"number":"000-111-2222"
},
{
"type":"mobile",
"number":"111-222-3333"
},
{
"type":"office",
"number":"333-444-5555"
}
]
}
Assertion Property | Actual Value |
username | Bret |
address.city | Gwenborough |
phoneNumbers[0].number | 000-111-2222 |
phoneNumbers[-1].number | 333-444-5555 |
phoneNumbers[*].number | 000-111-2222 (or) 111-222-3333 (or) 333-444-5555 |
Examples of data extraction from a JSON index-value response
The following is a sample JSON index-value response:
[
{
"type":"home",
"number":"000-111-2222"
},
{
"type":"mobile",
"number":"111-222-3333"
},
{
"type":"office",
"number":"333-444-5555"
}
]
Assertion Property | Actual Value |
[1].number | 111-222-3333 |
[-1].type | office |
XPATH Expressions
The following is a sample of XPath expressions:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<address>
<city>Gwenborough</city>
<geo>
<lat>-37.3159</lat>
<lng>81.1496</lng>
</geo>
</address>
<id>1</id>
<name>Leanne Graham</name>
<phoneNumbers>
<element>
<number>000-111-2222</number>
<type>home</type>
</element>
<element>
<number>111-222-3333</number>
<type>mobile</type>
</element>
<element>
<number>333-444-5555</number>
<type>office</type>
</element>
</phoneNumbers>
<username>Bret</username>
</root>
Assertion Property | Actual Value |
/root/username/text() | Bret |
/root/address/city/text() | Gwenborough |
/root/phoneNumbers/element[1]/number/text() | 000-111-2222 |
/root/phoneNumbers/element[3]/number/text() | 333-444-5555 |
/root/phoneNumbers/element/number/text() | 000-111-2222 (or) 111-222-3333 (or) 333-444-5555 |
Comparisons
The following operators let you compare actual and expected values. The comparison field is a dropdown menu from which you can select the required operator.
Equals
Not Equals
Contains
Not Contains
Is Empty
Is Not Empty
Lesser Than
Greater Than
Lesser Than or Equal To
Greater Than or Equal To