skip to content

Karate API testing

4 roadmaps90 questionsupdated

A Gherkin-flavoured DSL for API tests with no step definitions to write: payload matching, reusable feature calls, and a mock server in the same tool. Interviewers ask when that trade pays.

on this pageshow

guide

overview

~1 min

Karate is a test tool for HTTP APIs in which a Gherkin-style feature file is the entire test. The keywords that set a URL, send a request and check the reply ship with the tool, so no layer of Java step definitions sits behind the sentences. Interviewers ask about it for two reasons. The short syntax hides precise semantics — which step sends the call, what state survives it, how strict a comparison is — and candidates who have only copied examples trip on them. And choosing Karate is a trade: readable, glue-free tests in exchange for compile-time checks and the typed helpers of a library. The hub splits five ways. [Glue-free execution](/topics/dev-karate-glue) is how a line becomes an action: step prefixes, the built-in HTTP keywords, and scenarios driven by example rows. [Payload matching](/topics/dev-karate-assert), the largest section, is the one-step assertion over a whole response and the ways to loosen it. [Reuse and defaults](/topics/dev-karate-reuse) covers where a scenario gets values it never wrote: called features, the config file and `configure`. [Mock mode](/topics/dev-karate-mock) turns a feature file into a server. [Adoption and wiring](/topics/dev-karate-fit) is the Java runner that starts a suite, and the case for or against the tool. Junior rounds check that you can read a scenario and predict what it does. Middle rounds move to scope and strictness: which header is still set on the second call, why a nested comparison failed. Senior and principal rounds turn to mocks under concurrency, CI wiring, and whether a team should adopt Karate at all. Learn how steps execute and how `match` compares first, then reuse and configuration. The mock and the runner make sense once those are solid.

primer

### The feature file is the program Karate ships a closed set of step keywords — `url`, `path`, `request`, `method`, `match`, `def`, `call`, `configure` and more — and a step runs whichever keyword it starts with after the prefix. `Given`, `When`, `Then` and the bare `*` are there for readers and reports; they select nothing. That removes the glue layer a Cucumber suite needs, and it moves the extension point: logic with no keyword is written as JavaScript in the step or reached in Java through interop, never registered as a new keyword. ### A request is described, then sent Steps before `method` only describe the request; `method` is the one that goes on the wire, and `status` and `match` then read what came back. After each call most per-request settings are cleared, so a scenario that makes several calls has to know what survives. Defaults meant to outlive one call belong to `configure`, not to a single step. ### One match states a whole payload `match` compares an actual value against an expected literal in one recursive step, and the operator decides how strong the claim is: equality, containment, or containment that also reaches into nested values. Values that change every run are replaced by markers that assert type or shape, and by small JavaScript predicates. Interviewers probe this boundary hard — an extra key, array order, a missing key against a null — because a suite that is too strict breaks on harmless changes and one that is too loose passes a broken API. ### Values arrive from outside the scenario A scenario rarely sees all its inputs written in it. `karate-config.js` runs before each top-level scenario and seeds variables per environment; a called feature either shares its variables with the caller or hands them back as a map; `callonce` and `karate.callSingle()` cache expensive setup, such as a login, at different widths. This is where a suite hides its setup, and where debugging starts when a value is not what the scenario text suggests. ### The same syntax can serve In mock mode a feature file becomes an HTTP server. Each `Scenario` name is an expression tested against the incoming request, and the matched scenario sets response variables rather than returning an object. State can persist between requests, so a mock can fake a small stateful service. The handler serialises requests, which bounds what it can stand in for, and interviewers ask where that bound sits. ### Text instead of types Steps are text and expressions are JavaScript, so a renamed field or a misspelt variable surfaces when the scenario runs, not when the project compiles. That is the price of the readability, and the centre of every adoption question.

Feature file
A Gherkin-syntax text file holding one or more scenarios. In Karate it is the complete test, with no step-definition code behind it.
Step keyword
The built-in word after a step's prefix, such as def, match or method, that decides what the step does. The set is fixed and cannot be extended.
Background
Steps that run before each scenario of a feature. In a mock feature they run once, when the server starts.
Scenario Outline
A scenario repeated once per row of its Examples table, with each column bound as a variable for that run.
match
The assertion keyword that compares an actual value with an expected one, using an operator such as ==, contains or contains deep.
Fuzzy marker
A string such as '#string' or '#uuid' placed in an expected value, asserting the type or shape of the actual value instead of its content.
Embedded expression
A '#(...)' placeholder inside JSON or XML that is evaluated at run time, so the substituted value keeps its type.
karate-config.js
A file holding a JavaScript function that returns a map; its keys become variables in every top-level scenario. Environment-specific variants can extend it.
karate.env
The environment name, set by a system property or the runner, that selects the environment-specific config file and filters environment tags.
call and callonce
Keywords that run another feature and use its variables. callonce caches the result for the rest of the calling feature file.
configure
The keyword, or karate.configure() in JavaScript, that sets defaults such as headers, timeouts and retry behaviour which outlast a single request.
Mock feature
A feature file served as an HTTP server: scenario names are request-matching expressions, and response variables build each reply.
Runner builder
The Java API, opened with Runner.path(), that selects features and tags, sets options, and runs a suite on several threads.

Follow one run. A Java entry point — the `Runner` builder, or a JUnit method annotated `@Karate.Test` — selects features by path and tag and starts them, in parallel when asked. Before each top-level scenario Karate evaluates the config chain and binds the keys it returns, so `baseUrl` or a credential is in scope before the first step. The `Background` runs next; it is the usual home for a cached login and for `configure` defaults that every request should carry. The scenario then describes a request, sends it with `method`, and asserts with `status` and `match`. A `Scenario Outline` repeats all of this once per example row. Reports are written to the build directory, and CI finds them only if the runner was told to emit the format CI reads. Mock mode reuses the same parts rather than adding new ones: `def`, `match` and JavaScript run inside a server whose `Background` executes once at start-up instead of per scenario. A test can start a mock with `karate.start()` and point its `url` at the port the mock bound, so the fake and the tests that use it live in one suite. The Gatling bridge reuses a feature file as a load script in the same spirit. ```gherkin Background: * url baseUrl * def auth = callonce read('classpath:auth/login.feature') * configure headers = { Authorization: '#(auth.token)' } Scenario: create an order Given path 'orders' And request { sku: 'A-17', qty: 2 } When method post Then status 201 And match response == { sku: 'A-17', qty: 2, id: '#uuid', createdAt: '#string' } ``` Almost every line leans on another section. `baseUrl` came from the config file, the token from a cached call, the header from `configure`, and the marker-filled literal from payload matching. A question that seems to be about one line is often really about where its value came from.

  1. Glue-Free Execution →

    How a line becomes an action: step prefixes, the built-in HTTP keywords, and which step actually sends the request.

  2. Payload Matching →

    The match step and its strictness levels, the largest section and the assertion nearly every scenario depends on.

  3. Reuse and Defaults →

    Where values a scenario never wrote come from: config files, called features, cached setup and configure.

  4. Java Launcher Builder →

    The Java runner that selects, parallelises and reports a suite, which is what a CI job actually invokes.

  5. Mock Mode →

    A feature file served as a fake API, easiest once request building, matching and variable scope are familiar.

  6. Trade-Offs Against Libraries →

    The adoption trade against Java libraries, best argued after you know what the tool does and costs.

  • Reading Given, When and Then as meaningful: Karate treats every prefix alike, and the keyword after the prefix decides what the step does.

  • Expecting a header or path set for one call to carry into the next; per-request settings are cleared after each method, so lasting defaults go through configure.

  • Assuming contains stays lenient all the way down: nested objects and arrays revert to equality unless you use contains deep.

  • Writing '#null' to mean the key may be missing: that marker needs the key present. Absence is asserted with '#notpresent'.

  • Putting a query string inside path: the question mark is encoded into the segment and the server quietly sees a different URL. Use param.

  • Writing a mock Scenario expression that returns a truthy value such as a string; only a real boolean true selects that scenario.

  • Logging in with a plain call in the Background and blaming the API for a slow suite; callonce or karate.callSingle() is the cache.

  • Simulating latency by sleeping inside a mock scenario, which stalls every other client; set responseDelay instead.

  • Presenting Karate as strictly better than a Java library: it trades compile-time checking and typed helpers for readability, and some suites need those more.

Karate is usually placed against three kinds of tool. Against Java API libraries such as REST Assured, the trade is the glue layer and the compiler: a library test is ordinary Java, with types, refactoring and IDE checks, while a Karate test is a feature file that people outside the codebase can read and review, at the cost of those checks. Against Cucumber, Karate keeps the Gherkin shape but drops step definitions, so it fits API checks rather than business-language specifications that a team binds to its own code. Against Postman collections, both favour quick, readable requests; Postman is built around a graphical client, while Karate tests are text files in the repository, reviewed and versioned like code. Two side capabilities widen the comparison. Mock mode overlaps with dedicated HTTP stubbing tools such as WireMock, which make stubbing their whole job; Karate's argument is one syntax for both sides of a contract. The Gatling integration reuses feature files as load scripts instead of a separate simulation, a convenience whose limits [Trade-Offs Against Libraries](/topics/dev-karate-fit-choice) examines. A strong answer names the team and the suite before naming the tool.

explore

report an issue with this guide →

questions

90 · 5 sections

A Karate scenario reads `Given url 'https://api.example.com'`, `And path 'cats'`, `And request { name: 'Billie' }`, `When method post`, `Then status 201`. Which of those steps actually puts a request on the wire, and what does the `status` step do?

level: juniorimportance: must knowfreq 84%
basics
~20 s

The method step sends it. The url, path and request steps only accumulate state on Karate's request builder; method is what fires the call. The status step then asserts the response code and fails if it is anything else.

open as a page

In a Karate feature file, what does a step that begins with a bare `*` — such as `* def id = 5` — mean, and what changes if you write `Given`, `When` or `Then` in front of it instead?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Nothing changes. Karate accepts six step prefixes - the bare asterisk plus Given, When, Then, And and But - and treats all six identically. The prefix never reaches the code that decides what a step does; it is read back only afterwards, by the report and the rest of the output.

open as a page

In a Karate `Scenario Outline` step, what is the difference between writing `<name>` and `'#(name)'`, and which one preserves the column's type?

level: middleimportance: must knowfreq 52%
basics
~20 s

In Karate, <name> is a text substitution: the raw cell text is spliced into the step before it runs. '#(name)' is an embedded expression evaluated at run time against the bound variable, so the value keeps its type.

open as a page

In a Karate feature file, what turns an `Examples:` table into a dynamic one — so its rows come from `read('cats.json')` or `karate.setup()` instead of being typed out — and what must that cell evaluate to?

level: middleimportance: must knowfreq 60%
basics
~20 s

Karate treats an Examples table as dynamic only when it is a single cell: one column and one row, the header, with nothing under it. That cell is evaluated as JavaScript and must return a list of objects or a generator function.

open as a page

In a Karate `Examples:` table, what does appending `!` to a column header do, and what type does that column's value have without it?

level: middleimportance: must knowfreq 54%
basics
~20 s

A trailing ! on a Karate Examples column header makes each cell evaluate as a JavaScript value — number, boolean, or inline JSON. Without it the cell stays a plain string, and a blank cell becomes null.

open as a page

In a Karate feature file, what does `match response contains { id: 1 }` assert, and what does `match response.ids contains 23` assert when `ids` is a JSON array?

level: juniorimportance: must knowfreq 76%
basics
~20 s

Karate's contains asserts a subset. Against a JSON object, every expected key must exist with an equal value while extra actual keys are ignored. Against a JSON array, every expected item must appear somewhere, in any order.

open as a page

In a Karate feature file, what does the step `* match order == { id: 1, name: 'Billie' }` assert, and what happens if `order` also carries a `role` key?

level: juniorimportance: must knowfreq 84%
basics
~20 s

Karate's match == compares the entire payload in one recursive step: every key and value must correspond exactly. An extra role key fails the step, because == is a strict whole-payload comparison, not a subset check.

open as a page

In a Karate feature file, what forms can the left-hand side of a `match` step take, and what does a bare `$` refer to there?

level: juniorimportance: must knowfreq 82%
basics
~20 s

The left side of a Karate match step is a variable name, a JsonPath or XPath rooted at a variable such as response.name, a function or method call, or parenthesised JavaScript. A bare $ stands for the response, and a left side that starts with / is a bare XPath rooted there too.

open as a page

In a Karate feature file, the response carries a server-generated `id` and a `createdAt` timestamp that differ on every run. How do you still assert the entire payload in a single `match` step?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Put marker strings where the unpredictable values would go: match response == { id: '#uuid', createdAt: '#string', name: 'Billie' }. A marker asserts the value's type or shape instead of its content, so one step still checks every key.

open as a page

In a Karate feature file, what does the expected value `'#? _ > 0'` assert inside a `match`, and what is `_` bound to while that expression runs?

level: juniorimportance: must knowfreq 58%
basics
~20 s

#? runs the JavaScript that follows it and passes only when the result is true. Karate binds _ to the actual value at that position, so '#? _ > 0' asserts that the value there is greater than zero.

open as a page

In a Karate feature file, a `Background` runs before every scenario — so how does `* def token = callonce read('auth-token.feature')` avoid re-running that feature for each one?

level: juniorimportance: must knowfreq 70%
basics
~20 s

callonce runs the called feature only the first time and caches what it returned, so every later scenario in that feature file reuses it. Plain call re-executes the login for every scenario and every Examples row.

open as a page

In a Karate feature suite, what must the `karate-config.js` file contain, and what does Karate do with the value it produces?

level: juniorimportance: must knowfreq 78%
basics
~20 s

karate-config.js holds a JavaScript function that returns a map. Karate evaluates it before every top-level scenario and applies each key of that map as a scenario variable, so no step-definition or glue class is involved.

open as a page

In a Karate feature file, what is the difference between the step `* configure headers = { 'X-Trace': 'abc' }` and the step `* header X-Trace = 'abc'`?

level: juniorimportance: must knowfreq 70%
basics
~20 s

configure headers sets a default header map that Karate re-applies to every later request in scope. The header step sets one header on the request being built, and Karate clears it as soon as that call completes.

open as a page

In a Karate feature file, what is the difference between `* call read('login.feature')` and `* def auth = call read('login.feature')`?

level: juniorimportance: must knowfreq 70%
basics
~20 s

The def assignment decides scope. A bare call read('login.feature') merges every variable the called feature defined into the caller; def auth = call read('login.feature') isolates the call and hands those variables back as a map instead.

open as a page

In Karate, how do `callonce` and `karate.callSingle()` differ in how wide their cache is and in what each one uses as the cache key?

level: middleimportance: must knowfreq 62%
basics
~20 s

callonce caches per feature and keys on the call expression exactly as written. karate.callSingle() caches per suite, so once for the whole run across every feature, and keys on the path string you pass it.

open as a page

In a Karate mock feature - the kind served by `karate.start()` or a `MockServer` - when do the `Background` steps run?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Once, when the mock server starts. Karate executes a mock feature's Background while the handler is being built, before the first request arrives; every request afterwards runs only the steps of the one Scenario whose name matched.

open as a page

In a Karate mock feature file, what is the text after `Scenario:` used for, and what does the mock return when no `Scenario` matches the incoming request?

level: juniorimportance: must knowfreq 66%
basics
~20 s

In a Karate mock feature the Scenario name is a JavaScript expression evaluated per request, not a label. Scenarios are tried in file order; the first one returning true answers, and if none does the mock replies 404.

open as a page

In a Karate mock feature file, how does a matched Scenario produce the HTTP reply — what do you write instead of returning a response object?

level: juniorimportance: must knowfreq 72%
basics
~10 s

A mock scenario returns nothing. It assigns ordinary variables — response, responseStatus, responseHeaders, responseDelay — and after the last step Karate reads them and assembles the reply, so declaration order does not matter.

open as a page

A Karate mock feature has to remember data between HTTP requests. Where does that state live, and what puts it there?

level: middleimportance: must knowfreq 60%
basics
~20 s

In a map of global variables owned by the mock handler. The Background seeds it once at start-up, and after every matched Scenario the handler copies that request's variables back, so a def inside a Scenario survives too.

open as a page

In a Karate mock feature, what does `Scenario: pathMatches('/cats/{id}')` match, and where does the `id` value become available?

level: middleimportance: must knowfreq 58%
basics
~20 s

It matches a request path of exactly two segments whose first is literally cats, capturing the second under the name id. On a successful call the helper fills the pathParams map, so the scenario body reads pathParams.id as a string.

open as a page

Karate and a Java API-testing library such as REST Assured both drive HTTP calls and assert on responses. What is written differently in a Karate project, and what does that remove?

level: juniorimportance: must knowfreq 72%
basics
~20 s

In Karate the test is a .feature file whose steps are the framework's own keywords, so there is no step-definition layer to write: the HTTP call, the request payload and the assertion all live in that one file.

open as a page

In Karate, what does the Java line `Runner.path("classpath:animals").tags("@smoke").parallel(5)` actually do, and why does this class need no step-definition or glue package?

level: juniorimportance: must knowfreq 76%
basics
~20 s

Runner.path() opens Karate's builder, each chained call sets one option, and parallel(n) is the terminal call that discovers the features, runs them on n threads and returns a result object. No glue package is involved.

open as a page

A team moves its API suite from a Java library like REST Assured onto Karate feature files. Which compile-time guarantees does that give up, and what does Karate offer in their place?

level: middleimportance: must knowfreq 58%
basics
~10 s

Every compile-time guarantee goes: a Karate step is text and its expressions are JavaScript, so variable, field and method names are unchecked until the scenario runs. Karate replaces them with runtime failure and Java.type.

open as a page

In a Karate Java runner, what does `Runner.path("classpath:api").tags("@smoke,@sanity", "~@wip")` select, and how do the comma, the tilde and the two separate arguments each combine?

level: middleimportance: must knowfreq 68%
basics
~10 s

That chain runs scenarios tagged @smoke or @sanity but not @wip. Separate arguments are ANDed, a comma inside one argument means OR, and a leading tilde negates that whole argument.

open as a page

In Karate's JUnit integration, what is the `@Karate.Test` annotation, where may it be placed, and what must the annotated method return?

level: juniorimportance: should knowfreq 42%
basics
~10 s

Karate's @Karate.Test is a method-level annotation meta-annotated with JUnit's @TestFactory. The method must return a Karate instance, an Iterable of dynamic nodes, so each feature and scenario becomes its own test.

open as a page