Test Assertions in Karate API Test Script
Test Assertions in Karate API Test Script
In Karate, assertions are used to validate the API responses. Karate provides simple, readable syntax to perform various types of test validations in your scripts.
Steps to create Karate API test script are as follows:
β Common Karate Assertion Keywords
match
β Strict comparisonmatch contains
β Partial matchmatch each
β Match every item in an arraymatch !contains
β Negative matchassert
β JavaScript-style custom assertion
π Simple Assertion with match
Feature: Sample API test
Scenario: Validate response fields
Given url 'https://jsonplaceholder.typicode.com/posts/1'
When method get
Then status 200
And match response.userId == 1
And match response.id == 1
π Assert Full JSON Object
* def expected = { userId: 1, id: 1, title: '#string', body: '#string' }
* match response == expected
π Assert Using contains
* match response contains { userId: 1 }
π Negative Assertion
* match response !contains { userId: 999 }
π JavaScript Style Assertions
* assert response.userId == 1
* assert response.title.length > 0
π Array Assertions
* def response = [1, 2, 3, 4]
* match response contains 2
* match response == [1, 2, 3, 4]
* match response[0] == 1
π Match with Wildcards
* def expected = { id: '#number', title: '#string', completed: '#boolean' }
* match response == expected
π‘ Tip:
You can combine multiple assertions for comprehensive validation:
Then status 200
And match response.id == 1
And assert response.title != null
And match response.body contains 'some expected text'