Karate BDD API Testing: Writing Readable Tests with Gherkin
Karate uses Gherkin syntax — the same Feature/Scenario/Given/When/Then format as Cucumber. But Karate's relationship with BDD is different from Cucumber's. Understanding that difference helps you use Karate the way it was designed to be used.
Karate vs Cucumber: Different Goals
Cucumber is a collaboration tool. It's designed so that business stakeholders write feature files in plain English, and developers implement step definitions behind them. The promise: executable specifications that non-technical people can read and contribute to.
Karate uses Gherkin for a different reason: it's a readable, structured format for HTTP operations. You're not mapping English sentences to code. The steps are the code — Karate's keywords have direct meanings (method GET sends an HTTP GET request, status 200 asserts the status code).
The practical implication: in Cucumber, if you write And the response contains 'Alice', you need to implement a step definition. In Karate, And match response.name == 'Alice' just works — no implementation needed.
Anatomy of a Karate Feature File
Feature: User Management API
Background:
* url 'https://api.example.com'
* def adminToken = 'Bearer admin-token-123'
@smoke
Scenario: Get all users returns a list
Given path '/users'
When method GET
Then status 200
And match response == '#[]'
@regression
Scenario: Create a user with valid data
Given path '/users'
And header Authorization = adminToken
And request
"""
{
"name": "Alice Johnson",
"email": "alice@example.com",
"role": "editor"
}
"""
When method POST
Then status 201
And match response.id == '#number'
And match response.name == 'Alice Johnson'
And match response.createdAt == '#present'Feature
One feature per file. The feature name is descriptive — it appears in reports and helps you find failing tests.
Background
Runs before every scenario in the file. Use it for:
- Setting the base URL
- Defining shared variables
- Setting up auth tokens
Background steps don't use Given/When/Then — they use * (which means "step").
Tags
@smoke, @regression, @slow — arbitrary labels you assign to scenarios. Run subsets by tag:
mvn test -Dkarate.options="--tags @smoke"
mvn test -Dkarate.options="--tags ~@slow" # exclude slow testsBDD-Style Test Structure
Well-written Karate scenarios follow the same Given/When/Then thinking as BDD:
- Given — setup state (URL, headers, request body)
- When — execute the action (HTTP method)
- Then — assert the outcome (status code, response body)
Scenario: Delete a user requires admin role
# Given: authenticated as a non-admin user
Given path '/users/42'
And header Authorization = 'Bearer user-token'
# When: attempting to delete
When method DELETE
# Then: the server denies the request
Then status 403
And match response.error == 'Forbidden'
And match response.message == '#string'The comments are optional — Karate tests are already readable without them. But the structure helps when tests get complex.
Scenario Outline for Data-Driven Tests
The BDD pattern for parameterized tests is Scenario Outline + Examples:
Feature: User Role Validation
Scenario Outline: Creating users with different roles
Given url 'https://api.example.com'
And path '/users'
And header Authorization = 'Bearer admin'
And request { name: '<name>', email: '<email>', role: '<role>' }
When method POST
Then status <expectedStatus>
And match response.role == '<expectedRole>'
Examples:
| name | email | role | expectedStatus | expectedRole |
| Alice | alice@example.com | admin | 201 | admin |
| Bob | bob@example.com | editor | 201 | editor |
| Charlie | charlie@example.com | viewer | 201 | viewer |
| Dave | dave@example.com | invalid | 400 | #notpresent |Each row runs as a separate scenario. Reports show each row as a distinct test case with its inputs and outcome.
Calling Features from Features (BDD Composition)
In Cucumber, composition happens through shared step definitions. In Karate, you call feature files directly:
# auth.feature — reusable login flow
Feature: Authentication
Scenario: Login as admin
Given url 'https://api.example.com'
And path '/auth/login'
And request { username: 'admin', password: 'secret' }
When method POST
Then status 200
* def token = response.token# users.feature — uses auth
Feature: Users API
Background:
* def authResult = call read('classpath:features/auth/auth.feature')
* def token = authResult.token
Scenario: Get users as authenticated admin
Given url 'https://api.example.com'
And path '/users'
And header Authorization = 'Bearer ' + token
When method GET
Then status 200The call read(...) pattern is Karate's way of calling other feature files. You can pass arguments in and get variables back.
Passing Data Between Features
# create-user.feature
Feature: Create User
Scenario: Create a user
Given url 'https://api.example.com'
And path '/users'
And request __arg # __arg receives passed-in data
When method POST
Then status 201
* def userId = response.id# users-workflow.feature
Feature: User Workflow
Scenario: Full user lifecycle
* def createResult = call read('create-user.feature') { name: 'Alice', email: 'alice@example.com' }
* def userId = createResult.userId
Given url 'https://api.example.com'
And path '/users/' + userId
When method GET
Then status 200
And match response.name == 'Alice'
Given path '/users/' + userId
When method DELETE
Then status 204Assertions: BDD Thinking Applied
BDD emphasizes asserting behavior, not just presence. Good Karate assertions:
# Weak — just checks the field exists
And match response.createdAt == '#present'
# Better — checks the field has the right type and reasonable value
And match response.createdAt == '#string'
And match response.id == '#number'
And assert response.id > 0
# Best — checks business behavior
And match response.status == 'active'
And match response.permissions contains 'read'
And match response.permissions contains 'write'For negative cases (BDD also covers unhappy paths):
Scenario: Creating a user with duplicate email fails
* def existingEmail = 'existing@example.com'
Given url 'https://api.example.com'
And path '/users'
And request { name: 'Bob', email: '#(existingEmail)' }
When method POST
Then status 409
And match response.error == 'EmailAlreadyExists'
And match response.field == 'email'
And match response.value == existingEmailUsing JavaScript for Complex Logic
Karate lets you embed JavaScript when the built-in keywords aren't enough:
Scenario: Validate response timestamps
Given url 'https://api.example.com'
And path '/users/1'
When method GET
Then status 200
* def isRecentDate = function(dateStr) {
var date = new Date(dateStr);
var now = new Date();
var diffDays = (now - date) / (1000 * 60 * 60 * 24);
return diffDays < 365; // created within the last year
}
And assert isRecentDate(response.createdAt)Keep JavaScript in features minimal — complex logic belongs in shared JavaScript files that you load with read().
Organizing Feature Files for BDD Projects
A clean structure mirrors your API's domain:
src/test/java/
karate-config.js
features/
auth/
auth.feature # shared login scenarios
users/
users.feature # user CRUD
user-roles.feature # permission scenarios
orders/
orders.feature
order-lifecycle.feature
shared/
cleanup.feature # teardown helpersTag consistently so you can run subsets:
@smoke— critical path, runs in < 2 minutes@regression— full suite, runs in CI@contract— schema validation tests@security— auth/authz scenarios
What to Avoid
Mixing Karate and Cucumber step definitions. Karate is standalone. You can't mix it with Cucumber's step registry.
Overly granular features. One feature per HTTP resource, not one feature per endpoint. Users belong in users.feature, not get-users.feature, create-user.feature, etc.
Duplicating setup across scenarios. Use Background for shared setup. Use call read() for shared flows.
Asserting only happy paths. BDD's strength is documenting both success and failure paths. Every business rule that produces a 4xx error deserves a scenario.