Testing / Karate Framework Interview questions
How does Karate's mock server handle stateful request/response scenarios?
Because a Karate mock feature is really just a set of scenarios matched against incoming requests, and each scenario has full access to Karate's variable and JavaScript capabilities, a mock can maintain state across multiple requests within a single test run, not just return a fixed canned response every time.
Background: * def users = {} Scenario: pathMatches('/users') && methodIs('post') * def id = java.util.UUID.randomUUID() + '' * users[id] = request * karate.response.status = 201 * karate.response.body = { id: '#(id)' } Scenario: pathMatches('/users/{id}') && methodIs('get') * def user = users[pathParams.id] * karate.response.status = user ? 200 : 404 * karate.response.body = user
The users map defined in the Background persists across incoming requests handled by the same running mock instance, so a POST that creates a resource and a subsequent GET for that same resource behave consistently with each other, letting a mock simulate realistic multi-step workflows, like create-then-retrieve or create-then-update-then-delete, rather than only isolated, stateless responses.
More Related questions...