Skip to main content

Command Palette

Search for a command to run...

πŸ₯‹ KarateBDD: Understanding `match` vs `assert`

Deep Dive with Real API Use Cases & Practice Exercises

Published
β€’5 min read
πŸ₯‹ KarateBDD: Understanding `match` vs `assert`

In API test automation, match and assert are two of the most powerful features of KarateBDD. While both validate data, they do so in fundamentally different ways.

In this guide, you'll:

  • Understand their differences

  • See real-world usage in component, integration, and E2E testing

  • Practice with 3 levels of hands-on exercises


πŸ“˜ Table of Contents

  1. What is match in Karate?

  2. What is assert in Karate?

  3. Key Differences Between match and assert

  4. Real-World API Testing Use Cases

  5. Practice Exercises (Beginner to Advanced)

  6. Conclusion


1️⃣ What is match in Karate?

match is used to compare actual vs expected data β€” especially JSON or XML structures.
It returns pass if the comparison succeeds and fail otherwise.

βœ… Simple Examples

* def response = { name: 'Alice', age: 30 }
* match response.name == 'Alice'  # βœ… Pass: exact match
* match response.name == 'Bob'    # ❌ Fail: value mismatch
* match response == { name: 'Alice', age: 30 }  # βœ… Pass: full object match
* match response == { name: 'Alice' }  # ❌ Fail: partial match is not allowed with `==`

πŸ” match Variants

  • contains – Partial match allowed
* match response contains { name: 'Alice' }  # βœ… Pass
* match response contains { name: 'Bob' }    # ❌ Fail
  • contains only – Must contain exactly these values (order doesn't matter)
* def roles = ['admin', 'editor']
* match roles contains only ['editor', 'admin']  # βœ… Pass
* match roles contains only ['admin']            # ❌ Fail
  • contains any – At least one value must match
* def tags = ['karate', 'api', 'testing']
* match tags contains any ['dev', 'karate']  # βœ… Pass
* match tags contains any ['qa', 'ops']      # ❌ Fail
  • !contains – Asserts absence of value
* def roles = ['user', 'guest']
* match roles !contains 'admin'  # βœ… Pass: 'admin' not present
* match roles !contains 'guest'  # ❌ Fail: 'guest' is present

2️⃣ What is assert in Karate?

assert is used for boolean condition validation.
It evaluates the condition and returns pass if true, otherwise fail.

βœ… Simple Examples

* def age = 25
* assert age > 18  # βœ… Pass
* assert age < 10  # ❌ Fail

🧠 More Use Cases

* def price = 150
* assert price >= 100 && price <= 200  # βœ… Pass

* def user = { name: 'Lannister' }
* assert typeof user.name == 'string'  # βœ… Pass

* def name = 'karate'
* assert name.length > 3       # βœ… Pass
* assert name.startsWith('k')  # βœ… Pass

πŸ”„ Key Differences

Featurematchassert
PurposeData structure comparisonBoolean condition check
Best ForJSON/XML/API response validationLogical rules, numeric/string checks
OutputDetailed diffPass/fail with message
StyleKarate BDD DSLJavaScript-style syntax

🌐 Real-World API Testing Use Cases

🧩 Component Test (Microservice level)

* def response = call read('get-user.feature')
* match response == { id: '#number', name: '#string' }  # βœ… Validate structure
* assert response.id > 0                                # βœ… Check value rule

πŸ”— Integration Test (Multiple APIs)

* def user = call read('get-user.feature')
* def orders = call read('get-orders.feature') { userId: user.id }

* match orders contains { userId: user.id }  # βœ… Data relationship
* assert orders.length > 0                   # βœ… Business expectation

πŸš€ End-to-End Test (Full business flow)

* def user = call read('register-user.feature')
* def order = call read('create-order.feature') { userId: user.userId }

* match order contains { status: 'confirmed', userId: user.userId }  # βœ… Flow integrity
* assert order.totalAmount > 0                                       # βœ… Rule enforcement

πŸ§ͺ Practice Exercises

🟒 Level 1 JSON Response

* def response = {
  "name": "Bob",
  "age": 28,
  "active": true
}

🟒 Level 1: Practice Assertions

#TaskAnswer
1Match a string valuematch response.name == 'Bob'
2Assert number is > 10assert response.age > 10
3Match full objectmatch response == { name: 'Bob', age: 28, active: true }
4Match with containsmatch response contains { active: true }
5Assert a boolean is trueassert response.active == true

🟑 Level 2 JSON Response

* def response = {
  "roles": ["admin", "editor"],
  "email": "test@gmail.com",
  "profile": {
    "name": "Alice",
    "country": null
  }
}

🟑 Level 2: Practice Assertions

#TaskAnswer
1Match role list with contains onlymatch response.roles contains only ['admin', 'editor']
2Assert email ends with "@gmail.com"assert response.email.endsWith('@gmail.com')
3Match nested JSON with optional keymatch response.profile contains { country: #null }
4Assert exclusion with !containsmatch response.roles !contains 'banned'
5Combine multiple assertsassert response.email != null && response.roles.length == 2

πŸ”΄ Level 3 JSON Response

* def response = [
  { "id": 1, "name": "Item1", "quantity": 50 },
  { "id": 2, "name": "Item2", "quantity": 75 },
  { "id": 3, "name": "Item3", "quantity": 25 }
]

πŸ”΄ Level 3: Practice Assertions

#TaskAnswer
1Match each array object structurematch each response == { id: '#number', name: '#string', quantity: '#number' }
2Assert unique IDsassert karate.distinct(response, x => x.id).length == response.length
3Match using regexmatch response[0].name == '#regex ^Item\\d$'
4Assert total quantity > 100assert response[0].quantity + response[1].quantity + response[2].quantity > 100
5Validate chained object integrityassert response[0].id == 1 && response[1].id == 2 && response[2].id == 3

βœ… Conclusion

  • Use match for validating structures and values.

  • Use assert for logic, math, conditions, and expressions.

  • Together, they build expressive, testable, and maintainable API checks.