Real-World Karate DSL Patterns: Advanced API Testing Techniques

Real-World Karate DSL Patterns: Advanced API Testing Techniques

Getting started with Karate DSL is straightforward. The documentation covers the basics well, and simple GET/POST tests come together quickly. The harder part is building a test suite that scales — handling auth across dozens of scenarios, managing test data, dealing with async operations, and keeping tests maintainable as the API evolves.

These are patterns from real Karate implementations. Not tutorials — solutions to problems you'll hit when your test suite grows beyond 20 scenarios.

Pattern 1: Centralized Auth with Token Caching

The naive approach authenticates in every feature file. With 50 feature files, that's 50 auth calls per test run. Slow, and unnecessary.

auth/get-token.feature:

@ignore
Feature: Get auth token (reusable)

Scenario: Authenticate and return token
  * url karate.properties['auth.url'] || 'https://api.example.com'
  * path '/auth/login'
  * request { username: '#(username)', password: '#(password)' }
  * method post
  * status 200
  * def token = response.accessToken
  * def refreshToken = response.refreshToken
  * def expiresAt = response.expiresAt

auth/session.js (token caching):

// Returns cached token or fetches new one
function getToken(username, password) {
  var cacheKey = username;
  var cached = karate.get('tokenCache_' + cacheKey);
  
  if (cached && cached.expiresAt > Date.now() + 60000) {
    return cached.token;
  }
  
  var result = karate.call('classpath:auth/get-token.feature', {
    username: username,
    password: password
  });
  
  karate.set('tokenCache_' + cacheKey, {
    token: result.token,
    expiresAt: new Date(result.expiresAt).getTime()
  });
  
  return result.token;
}

karate-config.js:

function fn() {
  var session = Java.type('com.example.test.Session');
  
  return {
    baseUrl: karate.env === 'prod' ? 'https://api.example.com' : 'https://staging.api.example.com',
    adminToken: karate.call('classpath:auth/get-token.feature', {
      username: 'admin@example.com',
      password: java.lang.System.getProperty('admin.password')
    }).token
  };
}

Any feature file:

Background:
  * url baseUrl
  * header Authorization = 'Bearer ' + adminToken

The admin token is fetched once at config initialization and available everywhere. For user-specific tokens, call get-token.feature per scenario with @ignore to suppress it from reports.

Pattern 2: Schema-Driven Response Validation

Hardcoding expected values in assertions creates brittle tests. Schema validation is more resilient:

schemas/user.json:

{
  "id": "#uuid",
  "email": "#regex .+@.+\\..+",
  "name": "#string",
  "role": "#string",
  "createdAt": "#number",
  "updatedAt": "#number",
  "profile": {
    "bio": "##string",
    "avatar": "##string"
  }
}

Usage:

* def userSchema = read('classpath:schemas/user.json')

Scenario: Get user matches schema
  Given path '/users/1'
  When method get
  Then status 200
  And match response == userSchema

Scenario: User list items match schema
  Given path '/users'
  When method get
  Then status 200
  And match each response.items == userSchema

The ## prefix marks optional fields — they can be absent or null. The # prefix marks required fields that must match the type.

Schema files become living documentation. Update the schema when the API changes; tests automatically catch violations.

Pattern 3: Polling for Async Operations

APIs that trigger async processing return immediately but complete later. Testing them requires polling.

utils/poll.feature:

@ignore
Feature: Poll until condition or timeout

Scenario:
  * def maxRetries = maxRetries || 10
  * def interval = interval || 1000
  * def attempts = 0
  
  * def pollFn =
    """
    function() {
      if (attempts >= maxRetries) {
        karate.fail('Polling timed out after ' + maxRetries + ' attempts');
      }
      attempts++;
      var result = karate.call(pollFeature, pollArgs);
      if (!conditionFn(result)) {
        java.lang.Thread.sleep(interval);
        return pollFn();
      }
      return result;
    }
    """
  
  * def pollResult = pollFn()

Using poll in a test:

Scenario: Export completes within 30 seconds
  # Start export
  Given path '/exports'
  And request { type: 'csv', filter: { status: 'active' } }
  When method post
  Then status 202
  * def exportId = response.id

  # Poll until complete
  * def pollFeature = 'classpath:features/get-export-status.feature'
  * def pollArgs = { exportId: exportId }
  * def conditionFn = function(result) { return result.status == 'complete' || result.status == 'failed' }
  * def pollConfig = { maxRetries: 30, interval: 1000 }
  * call read('classpath:utils/poll.feature') pollConfig
  
  # Verify completion
  Given path '/exports/' + exportId
  When method get
  Then status 200
  And match response.status == 'complete'
  And match response.downloadUrl == '#notnull'

get-export-status.feature:

@ignore
Feature: Get export status

Scenario:
  Given url baseUrl
  And path '/exports/' + exportId
  And header Authorization = 'Bearer ' + adminToken
  When method get
  Then status 200
  * def status = response.status

Karate's karate.call() returns feature variables. The poll loop checks the condition function and retries up to the limit.

Pattern 4: Test Data Management

Tests that create data leave it behind. Without cleanup, test data accumulates and scenarios start interfering.

Cleanup pattern using karate.configure(afterScenario):

Feature: User creation tests

Background:
  * url baseUrl
  * header Authorization = 'Bearer ' + adminToken
  * def createdIds = []

Scenario: Create and verify user
  Given path '/users'
  And request { name: 'Test User', email: 'test-' + karate.epoch + '@example.com' }
  When method post
  Then status 201
  * createdIds.push(response.id)
  
  Given path '/users/' + response.id
  When method get
  Then status 200
  And match response.name == 'Test User'

Cleanup hook (in karate-config.js):

karate.configure('afterScenario', function() {
  var ids = karate.get('createdIds');
  if (ids && ids.length > 0) {
    ids.forEach(function(id) {
      karate.call('classpath:utils/delete-user.feature', { userId: id });
    });
  }
});

delete-user.feature:

@ignore
Feature: Delete user (cleanup)

Scenario:
  * url baseUrl
  * path '/users/' + userId
  * header Authorization = 'Bearer ' + adminToken
  * method delete
  * match responseStatus == 204 || responseStatus == 404

The 404 match handles cases where a test failed before creating the resource — don't fail cleanup because there's nothing to clean up.

Pattern 5: Environment-Aware Configuration

Tests that hardcode staging URLs break in CI. Tests that use environment variables break locally. The solution is layered configuration:

karate-config.js:

function fn() {
  var env = karate.env || 'local';
  
  // Base config
  var config = {
    logPrettyRequest: true,
    logPrettyResponse: true
  };
  
  // Environment-specific overrides
  if (env === 'local') {
    config.baseUrl = 'http://localhost:8080';
    config.adminPassword = 'localdev';
  } else if (env === 'ci') {
    config.baseUrl = java.lang.System.getenv('API_BASE_URL');
    config.adminPassword = java.lang.System.getenv('ADMIN_PASSWORD');
  } else if (env === 'staging') {
    config.baseUrl = 'https://staging.api.example.com';
    config.adminPassword = java.lang.System.getenv('STAGING_ADMIN_PASSWORD');
  }
  
  // Secrets from environment (never in source)
  config.stripeTestKey = java.lang.System.getenv('STRIPE_TEST_KEY');
  
  return config;
}

Running per environment:

# Local
mvn test

# CI
mvn test -Dkarate.env=ci

# Staging smoke test
mvn test -Dkarate.env=staging -Dkarate.options="--tags @smoke"

Pattern 6: Custom JavaScript Utilities

Karate allows JavaScript helpers for logic that's awkward in Gherkin:

utils/helpers.js:

function generateEmail() {
  return 'test-' + Date.now() + '-' + Math.floor(Math.random() * 1000) + '@example.com';
}

function generateOrderItems(count) {
  var items = [];
  for (var i = 0; i < count; i++) {
    items.push({
      productId: Math.floor(Math.random() * 100) + 1,
      quantity: Math.floor(Math.random() * 5) + 1
    });
  }
  return items;
}

function formatDate(offsetDays) {
  var d = new Date();
  d.setDate(d.getDate() + offsetDays);
  return d.toISOString().split('T')[0];
}

Usage in feature:

* def helpers = read('classpath:utils/helpers.js')
* def email = helpers.generateEmail()
* def items = helpers.generateOrderItems(3)
* def futureDate = helpers.formatDate(30)

Given path '/orders'
And request
  """
  {
    email: '#(email)',
    items: '#(items)',
    deliveryDate: '#(futureDate)'
  }
  """

Keep helpers focused on data generation and transformation. Don't put HTTP logic in JS — that belongs in feature files.

Pattern 7: Conditional Test Execution

Not every test runs in every environment. Feature flags, external services, and data dependencies require conditional execution:

Feature: Payment tests

Background:
  * def paymentsEnabled = karate.properties['payments.enabled'] != 'false'

Scenario: Process payment
  * if (!paymentsEnabled) karate.abort()
  
  Given path '/payments'
  And request { amount: 1000, currency: 'USD' }
  When method post
  Then status 200

karate.abort() skips the current scenario without marking it as failed. Use this for tests that require external services, specific test data, or features not deployed to all environments.

Pattern 8: GraphQL Testing

Karate handles GraphQL — it's just a POST request with a specific body structure:

Feature: GraphQL API tests

Background:
  * url 'https://api.example.com/graphql'
  * header Authorization = 'Bearer ' + token

Scenario: Query user by ID
  * text query =
    """
    query GetUser($id: ID!) {
      user(id: $id) {
        id
        name
        email
        orders {
          id
          total
          status
        }
      }
    }
    """
  
  Given request { query: query, variables: { id: '42' } }
  When method post
  Then status 200
  And match response.errors == '#notpresent'
  And match response.data.user.id == '42'
  And match response.data.user.orders == '#[]'

Scenario: Mutation creates user
  * text mutation =
    """
    mutation CreateUser($input: CreateUserInput!) {
      createUser(input: $input) {
        id
        name
      }
    }
    """
  
  Given request
    """
    {
      query: '#(mutation)',
      variables: {
        input: { name: 'Alice', email: 'alice@example.com' }
      }
    }
    """
  When method post
  Then status 200
  And match response.errors == '#notpresent'
  And match response.data.createUser.id == '#notnull'

The * text keyword reads a block as raw text without JSON parsing — required for GraphQL query strings that contain characters that would break JSON parsing.

Pattern 9: Response Time Assertions

Karate exposes response timing through responseTime:

Scenario: API responds within SLA
  Given path '/products'
  When method get
  Then status 200
  And assert responseTime < 500

Scenario: Slow endpoint is acceptable within 2 seconds
  Given path '/reports/generate'
  When method post
  Then status 202
  And assert responseTime < 2000

responseTime is in milliseconds. Use this sparingly — performance assertions in functional tests are fragile in shared CI environments. For systematic performance testing, use karate-gatling instead.

Pattern 10: Test Reporting and Categorization

Large test suites need organized reporting. Combine Karate's built-in reports with custom categorization:

@users @smoke @critical
Feature: User management

@happy-path
Scenario: Create valid user
  ...

@edge-case
Scenario: Create user with unicode name
  ...

@negative
Scenario: Create user with duplicate email
  ...

Generate targeted reports:

# Run only critical smoke tests
mvn test -Dkarate.options="--tags @smoke,@critical"

# Run everything except slow tests
mvn test -Dkarate.options="--tags ~@slow"

# Run user tests in CI, skip integration-dependent ones
mvn test -Dkarate.options="--tags @users,~@external"

Bringing It Together

These patterns don't require adopting all at once. Start with centralized auth (Pattern 1) — it solves an immediate problem in any Karate suite. Add schema validation (Pattern 2) as your API stabilizes. Introduce cleanup (Pattern 4) when test data conflicts start causing failures.

The patterns scale: a 10-scenario suite needs Pattern 1. A 200-scenario suite needs all of them.

For API suites running in production, the same patterns apply but the scope expands — auth tokens need to work with real production credentials, data cleanup matters even more, and monitoring continuously validates that your real-world Karate scenarios still pass against the live API. HelpMeTest provides that always-on layer: the same scenarios you run in CI, running every 5 minutes against production, catching drift before customers notice.

The investment in good Karate patterns pays back when you're adding scenario 50, not scenario 5. Build the infrastructure early.

Read more

Start now free