Skip to main content

CORE SYNTAX

Feature Files

Write tests using Gherkin syntax with built-in step definitions. Unlike traditional Cucumber, Karate requires no Java glue code - everything you need for API testing is included.

Basic Structure

Every Karate test follows this structure:

Gherkin
Feature: User Management API
Validate common user operations using a public REST API

Background:
* url 'https://jsonplaceholder.typicode.com'
* configure headers = { Accept: 'application/json; charset=utf-8' }

Scenario: Create a new user
Given path 'users'
And request { name: 'John Doe', email: 'john@example.com', username: 'jdoe' }
When method post
Then status 201

Scenario: Get a user by ID
Given path 'users', 1
When method get
Then status 200
And match response contains { id: 1 }
And match response.name == '#string'

Scenario: List all users
Given path 'users'
When method get
Then status 200
And match response == '#[10]'
And match response[0].email == '#string'

The Three Sections

Feature Declaration

Give your Feature a clear purpose so anyone can understand what part of the system is being tested.

Gherkin
Feature: Payment Processing API
Test payment workflows including validation,
processing, and error handling scenarios

Background (Optional)

Used to define common setup that runs before each scenario, like setting the base URL, default headers, and performance configs.

Gherkin
Background:
* url 'https://api.example.com'
* def authToken = karate.callSingle('classpath:auth/get-token.feature')
* header Authorization = 'Bearer ' + authToken.token
* configure connectTimeout = 5000
Important

Background variables are reset before each scenario. For one-time setup, use callonce or karate.callSingle().

Scenarios

Scenarios represent independent test cases, each validating one behavior:

Gherkin
Scenario: Process valid payment
Given path 'payments'
And request { amount: 100.00, currency: 'USD', cardToken: 'tok_123' }
When method post
Then status 200
And match response.status == 'succeeded'

Naming Conventions

File Naming

  • Feature files: kebab-case.feature (e.g., user-authentication.feature)
  • Descriptive names: Clearly indicate the feature area and purpose
  • Avoid abbreviations: user-mgmt.featureuser-management.feature

Scenario Naming

Gherkin
# Good: Descriptive scenario names
Scenario: Create user with valid email address
Scenario: Update user profile with missing required fields
Scenario: Delete user removes all associated data

# Avoid: Generic or unclear names
Scenario: Test user creation
Scenario: User test 1
Scenario: Happy path

Given-When-Then vs Star (*)

Karate supports both BDD-style syntax and technical step syntax. Choose the style based on who the test is written for.

Technical Style (*) for API Automation

Best used for day-to-day API, integration, and contract testing. Clear. Direct. No ceremony.

Gherkin
Scenario: Retrieve a user by ID
* url 'https://jsonplaceholder.typicode.com'
* path 'users', 1
* method get
* status 200
* match response.id == 1
* match response.name == '#string'

Given-When-Then for Business Context

Use when tests need to tell a story and align with business workflows.

Gherkin
Scenario: A user creates a new account successfully
Given url 'https://jsonplaceholder.typicode.com/users'
And request { name: 'Jane', email: 'jane@example.com' }
When method post
Then status 201
And match response contains { id: '#number' }

When to Use Which

  • Given-When-Then: Business-readable scenarios, stakeholder communication
  • Star (*): Technical API tests, Background sections, variable definitions

Script Structure

Karate vs Cucumber

AspectCucumberKarate
Step DefinitionsRequired Java glue codeBuilt-in for HTTP/JSON/XML
Maintenance2 layers (feature + Java)Single layer (feature only)
Learning CurveComplex setupImmediate productivity
API TestingRequires REST AssuredNative HTTP support

Comments and Documentation

Add comments only where they improve understanding. Use them to clarify business intent or complex logic, not to restate what the code already says.

Gherkin
Feature: Users API
# Create a new user successfully

Scenario: Create user - happy path
* url 'https://jsonplaceholder.typicode.com'
* path 'users'
* request { name: 'Jane', email: 'jane@example.com' }
* method post
* status 201 # User should be created

Best Practices

Scenario Outline for Data-Driven Tests

Use a Scenario Outline to run the same test logic with multiple datasets. This reduces repetition and makes behavior coverage more complete.

Gherkin
@smoke @createUser
Feature: Create User with Multiple Inputs

Scenario Outline: Validate creation of different users
* url 'https://jsonplaceholder.typicode.com'
* path 'users'
* request { name: '<name>', email: '<email>' }
* method post
* status 201
* match response contains { id: '#number' }

Examples:
| name | email |
| John | john@test.com |
| Jane | jane@test.com |
| Bob | bob@test.com |

Independent Scenarios

Each Scenario must run on its own without relying on data created by another test. This ensures stable results, especially when running tests in parallel or in CI pipelines.

Gherkin
Feature: Independent user tests
# Each test uses known, permanent data

Scenario: Create a new user
* url 'https://jsonplaceholder.typicode.com/users'
* request { name: 'Alice', email: 'alice@example.com' }
* method post
* status 201

Scenario: Retrieve a known user
* url 'https://jsonplaceholder.typicode.com/users/1'
* method get
* status 200
* match response.id == 1

Common Gotchas

  • Background resets: Variables in Background are reset before each scenario
  • Scenario independence: Each scenario should work standalone
  • Variable scope: Variables don't carry over between scenarios
  • Parallel execution: Scenarios may run in any order
Background and Parallel Execution

Variables defined in Background are reset before every Scenario. Combined with parallel execution, scenarios can run in any order on different threads.

Design for isolation:

  • Each scenario must be runnable independently
  • Don't share state between scenarios
  • Don't depend on execution order
  • Use callonce for one-time setup that needs to persist

See Variables and Parallel Execution for details.

Next Steps

Master feature file structure and continue with:

  • Variables - Learn data management and manipulation
  • Data Types - Handle JSON, XML, and complex data
  • Actions - Master Karate's built-in keywords