Resource library

QA Interview

Karate Mock Server Interview Questions (2026)

Master karate mock server interview questions on routing, state, proxying, auth, delays, CI, and 2026 APIs with runnable examples and expert grading tips.

25 min read | 3,480 words

TL;DR

A strong answer explains matching, request inspection, response construction, lifecycle, state, proxying, and test isolation. It also distinguishes a useful test double from a fake production service and supports claims with executable Karate v2 syntax.

Key Takeaways

  • Explain how Karate selects the first matching mock Scenario for each HTTP request.
  • Use pathMatches(), methodIs(), headerValue(), paramValue(), and bodyPath() to model request contracts.
  • Control the reply with response, responseStatus, responseHeaders, responseStatusText, and responseDelay.
  • Keep state in Background variables only when the test genuinely needs a stateful double.
  • Start embedded mocks on random ports to avoid collisions in local and parallel CI runs.
  • Use karate.proceed() for selective proxying, while monitoring contract drift against the real provider.
  • Treat mocks as trusted development tools, never as hardened public application servers.

These karate mock server interview questions prepare you to explain both syntax and design judgment. A strong candidate can route an incoming request, construct realistic success and failure responses, manage lifecycle and state, and show how the consumer test proves that the double behaves as intended.

The examples use the current Karate v2 API model and Java 21+ expectations. If you need a broader DSL refresher first, work through the Karate DSL tutorial, then return here and answer each question aloud with a concrete trade-off.

TL;DR

Topic Interview-ready point API or evidence
Routing The first matching Scenario handles the request pathMatches() and methodIs()
Inspection Prefer helpers over raw maps for common checks paramValue(), headerValue(), bodyPath()
Response Set the body, HTTP metadata, and optional latency explicitly response, responseStatus, responseHeaders, responseDelay
Lifecycle Mock Background runs once at startup Shared fixture state persists across requests
Startup Random ports remove local and CI collisions karate.start() returns an object with port
Proxying Stub selected traffic and forward the remainder karate.proceed()
Safety Run mocks only on controlled developer or CI networks A mock is not a hardened public server

The fastest study route is matching -> request variables -> response variables -> state -> faults -> proxy mode -> CI isolation. Compare the answers with the Karate DSL interview guide and practice converting each definition into a small working route.

1. Foundations: karate mock server interview questions

Q: What is a Karate mock server?

A Karate mock server is an HTTP test double whose routes and behavior can be declared in a Karate feature file or, in v2, a JavaScript handler. It accepts real network requests, selects a matching rule, and returns controlled bodies, statuses, headers, or delays. Teams use it to develop consumers before a provider is available, isolate failure scenarios, and remove unstable dependencies from focused tests.

Q: How is a mock different from a stub or fake?

A stub normally returns canned data, while a mock often verifies or reacts to specific interactions, and a fake implements a simplified working model such as an in-memory repository. Karate can express all three styles, so the label depends on the behavior you build. A static GET route is stub-like, a route that rejects the wrong header exercises interaction rules, and a CRUD feature with persistent state behaves like a fake.

Q: How does a Karate mock decide which Scenario handles a request?

Karate evaluates Scenario name expressions from top to bottom for every incoming request. The first expression that evaluates to true wins, and only that Scenario body runs. Conditions commonly combine pathMatches('/orders/{id}') with methodIs('get') or header and body predicates.

Q: Why does Scenario order matter?

A broad route can shadow a narrower route placed below it. For example, /users/{id} can capture /users/admin before an admin-specific response is considered. Put exact or highly constrained cases first, parameterized routes next, and the catch-all last.

2. Starting and stopping Karate test doubles

Q: How do you start a mock inside a Karate test?

feature')during setup and save the returned server object. Itsportproperty identifies the randomly allocated port, which you append tohttp://localhost:` for the consumer's base URL. An embedded start couples server lifetime to the test run and avoids a separately managed process.

Q: Why should an embedded mock normally use a random port?

A fixed port creates collisions when two developers, forks, or CI workers run the suite together. Asking the operating system for an available port makes parallel execution far more reliable. port` instead of duplicating a number in configuration.

Q: How do you start a standalone Karate mock from the CLI?

feature -p 8080when another process needs a stable local endpoint. Multiple-moptions can load more than one mock feature, and--ssl` enables HTTPS for a configured CLI run. A standalone process is convenient for frontend development but needs explicit process and port cleanup in automation.

Q: What is the Java API for creating a mock server in Karate v2?

build()and retain the returned instance.getPort()supplies the selected port, andstop()` releases resources after the tests finish. This API fits JUnit fixtures that need to configure a non-Karate client.

Runnable project used in the answers

Place these two files in the same directory. The mock provides deterministic catalog behavior, and the consumer feature starts it on a random port.

# catalog-mock.feature
@ignore
Feature: Catalog test double

Background:
  * def products = { 'p-1': { id: 'p-1', name: 'Keyboard', stock: 3 } }
  * configure responseHeaders = { 'Content-Type': 'application/json', 'X-Mock': 'catalog' }

Scenario: pathMatches('/products') && methodIs('get')
  * def response = karate.valuesOf(products)

Scenario: pathMatches('/products/{id}') && methodIs('get')
  * def product = products[pathParams.id]
  * def responseStatus = product ? 200 : 404
  * def response = product || { code: 'PRODUCT_NOT_FOUND', id: '#(pathParams.id)' }

Scenario: pathMatches('/products') && methodIs('post') && bodyPath('$.name')
  * def created = request
  * def id = 'p-' + (karate.sizeOf(products) + 1)
  * set created.id = id
  * set created.stock = created.stock || 0
  * eval products[id] = created
  * def responseStatus = 201
  * def responseHeaders = { 'Content-Type': 'application/json', 'Location': '/products/' + id }
  * def response = created

Scenario:
  * def responseStatus = 404
  * def response = { code: 'ROUTE_NOT_FOUND', path: '#(requestPath)' }
# catalog-client.feature
Feature: Catalog consumer against embedded mock

Background:
  * def mock = karate.start('catalog-mock.feature')
  * url 'http://localhost:' + mock.port

Scenario: Read a known product
  Given path 'products', 'p-1'
  When method get
  Then status 200
  And match header X-Mock == 'catalog'
  And match response == { id: 'p-1', name: 'Keyboard', stock: 3 }

Scenario: Create and retrieve a product
  Given path 'products'
  And request { name: 'Mouse', stock: 5 }
  When method post
  Then status 201
  And match header Location == '/products/p-2'
  And match response == { id: 'p-2', name: 'Mouse', stock: 5 }
  * def createdId = response.id
  Given path 'products', createdId
  When method get
  Then status 200
  And match response.name == 'Mouse'

Run karate catalog-client.feature. Verification succeeds when both scenarios pass and the report shows requests sent to a localhost URL with a dynamically chosen port.

3. Request matching and inspection questions

Q: What does pathMatches() return, and how are path parameters accessed?

pathMatches('/products/{id}') returns a boolean indicating whether the request path fits the pattern. id` without manually splitting the URI. The match uses the path, not the query string.

Q: How do you match query parameters?

Use paramExists('verbose') when presence alone changes behavior and paramValue('limit') when the route needs one value. The raw requestParams map stores lists, which matters for repeated parameters such as tag=api&tag=mock. Convert numeric text deliberately before using it in calculations.

Q: How do you check authorization and content negotiation headers?

Use headerContains('Authorization', 'Bearer') for a predicate and headerValue('Authorization') to retrieve the case-insensitive single value. typeContains('json') evaluates the request Content-Type, while acceptContains('xml') supports response negotiation. Do not index requestHeaders unless multiple header values are central to the case.

Q: How do you route on a JSON or XML request body?

action')evaluates JsonPath against JSON, and an expression beginning with/is treated as XPath for XML. The parsed body is also available asrequest` for field access or reuse in a response. Body-aware routing is useful for operation-style endpoints, but too many payload branches can become a second implementation of the provider.

4. Building realistic mock responses

Q: Which variables control a feature-file mock response?

Set response for the body, responseStatus for the HTTP code, responseStatusText for an optional reason phrase, and responseHeaders for headers. responseDelay adds a delay in milliseconds before the reply. JSON, XML, text, and bytes can be represented, with Karate serializing supported body types.

Q: How do you return dynamic response data without inventing unstable values?

Derive the response from explicit request fields, path parameters, or controlled server state. For example, echo the requested product ID in a 404 body or allocate the next ID from a counter initialized in Background. Avoid current timestamps unless time is the behavior under test, because they make exact assertions and snapshots noisy.

Q: How do you simulate latency?

Assign a millisecond value to responseDelay inside the matching Scenario. Karate v2 schedules mock delays without blocking a request thread, so several slow responses can coexist more efficiently than a sleep-based handler. Choose a delay just beyond the consumer's configured boundary when testing a timeout.

Q: What should happen when no route matches?

Without a matching Scenario, the client can wait until its connection or read timeout, which produces weak diagnostic evidence. Add an empty Scenario at the bottom as a catch-all and return a structured 404 containing a safe request path. The empty name expression evaluates as the fallback only because all more specific routes appear first.

5. Stateful Karate mock server design

Q: Why does Background behave differently in a mock feature?

A normal Karate test runs Background before each Scenario, but a mock executes it once when the server starts. Variables created there can therefore persist across incoming requests. That lifecycle enables counters, maps, and simple workflows, but it also introduces shared mutable state.

Q: How would you implement in-memory CRUD behavior?

Initialize a map and a next-ID value in Background, then give POST, GET, PUT, and DELETE their own method-specific routes. A create route validates mandatory fields before writing, returns 201 plus Location, and stores the object under a stable key. A delete route should distinguish 204 from 404 and avoid returning a JSON body with 204.

Q: What risks appear when stateful mocks receive concurrent requests?

Two creates can read and update the same counter, and one test can observe data written by another. Even if the map itself accepts both operations, consumer assertions tied to p-2 may become order-dependent. Prefer immutable fixtures for parallel tests or give each run a separate server instance and namespace.

Q: When should a mock preserve a state transition?

Preserve state when the consumer behavior depends on a sequence such as PENDING -> PAID -> SHIPPED. Reject invalid transitions with the same status and error shape promised by the provider contract. Do not model unrelated business calculations simply to make the double feel complete.

6. Errors, authentication, and resilience

Q: How do you model 401 and 403 responses correctly?

Return 401 when credentials are missing or invalid, and include a WWW-Authenticate header if the real API contract defines one. Return 403 when the identity is understood but lacks permission for the resource. Separate routes can use headerContains() for the accepted bearer shape and a fallback protected route for rejection.

Q: How would you simulate rate limiting?

Create a constrained route that returns 429 and a deterministic Retry-After header. If retry behavior depends on a sequence, maintain a small hit counter and return success after a known number of throttled responses. Keep the wait small enough for the test suite while preserving the unit expected by the client.

Q: Is karate.abort() a good way to represent an HTTP timeout?

abort()` in a mock Scenario ends processing without a response, so the client experiences a timeout-like failure. It is useful for testing transport handling, but it provides less diagnostic clarity than a delayed endpoint when you are validating a read-timeout boundary. Name the test after the failure mode and configure a short client timeout.

Q: How do you support a browser client calling the mock?

Set configure cors = true in the mock Background when cross-origin browser requests are expected. Karate then supplies CORS response behavior, including preflight support, without hand-coding every OPTIONS route. Test the browser's actual origin and headers because permissive local behavior can differ from production policy.

Here is a runnable fault feature you can start with karate mock -m fault-mock.feature -p 8090. Verify it with curl -i http://localhost:8090/limited and confirm status 429, Retry-After: 1, and the JSON code.

# fault-mock.feature
@ignore
Feature: Consumer resilience fixtures

Background:
  * configure cors = true
  * configure responseHeaders = { 'Content-Type': 'application/json' }

Scenario: pathMatches('/limited') && methodIs('get')
  * def responseStatus = 429
  * def responseHeaders = { 'Content-Type': 'application/json', 'Retry-After': '1' }
  * def response = { code: 'RATE_LIMITED' }

Scenario: pathMatches('/slow') && methodIs('get')
  * def responseDelay = 1500
  * def response = { status: 'ready' }

Scenario: pathMatches('/protected') && methodIs('get') && headerContains('Authorization', 'Bearer test-token')
  * def response = { subject: 'qa-user', scope: 'catalog:read' }

Scenario: pathMatches('/protected')
  * def responseStatus = 401
  * def responseHeaders = { 'Content-Type': 'application/json', 'WWW-Authenticate': 'Bearer realm="catalog"' }
  * def response = { code: 'UNAUTHORIZED' }

7. Proxying and contract-testing questions

Q: What does karate.proceed() do in a mock?

proceed(targetUrl)` forwards the current HTTP exchange to a backend and populates the mock's response variables from the provider reply. The Scenario can then return the result unchanged or alter selected fields. Calling it without a URL uses the original host in a true proxy arrangement.

Q: How do you implement selective proxying?

Place explicit stub routes before a general forwarding Scenario. proceed()`. This pattern lets a team override one difficult provider response without reproducing the entire API.

Q: Is a Karate mock a consumer-driven contract test?

Not by itself. A mock executes an expectation, while a contract test also needs an authoritative, shareable agreement and provider-side verification. Karate can express consumer examples and validate schemas, but teams must still decide how the provider proves compatibility.

Q: How do you prevent the mock from drifting away from production?

Derive fixtures from reviewed API specifications or provider-approved examples, then run a smaller compatibility suite against the real service. Version contract changes, assign owners, and fail review when mock updates lack provider evidence. Production observations can reveal headers or error shapes missing from the double, provided sensitive payloads are sanitized.

A selective proxy can be expressed in a complete feature. Start it only when http://real-backend:8080 is a controlled test provider, then request /api/catalog/sold-out to get the stub and another /api/catalog/... path to exercise forwarding.

# catalog-proxy.feature
@ignore
Feature: Selective catalog proxy

Background:
  * def backendUrl = 'http://real-backend:8080'

Scenario: pathMatches('/api/catalog/sold-out') && methodIs('get')
  * def responseStatus = 409
  * def response = { code: 'OUT_OF_STOCK', sku: 'sold-out' }

Scenario: pathMatches('/api/catalog/{resource}')
  * karate.proceed(backendUrl)
  * def responseHeaders = { 'X-Test-Proxy': 'true' }

8. Consumer tests, UI tests, and CI

Q: What should a consumer test assert when it uses a mock?

Assert the outgoing method, path, headers, and body through behavior the route requires, then assert how the consumer interprets the returned contract. Checking only that the mock responded proves little about application behavior. A UI test might confirm that a 409 code renders an out-of-stock message and disables checkout.

Q: When is driver.intercept() useful?

Karate's Chrome driver can intercept matching browser requests and delegate them to a mock feature or inline handler. Set interception before navigating to the application so early API calls are not missed. This keeps a frontend scenario focused when the real backend is unavailable or an edge response is hard to create.

Q: Can stateful mock tests run in parallel?

They can when each scenario owns a distinct server or unique data namespace. Sharing one catalog map across parallel scenarios makes read-after-write assertions dependent on scheduling. Tag truly serial workflows or redesign them around immutable fixtures before reducing global thread count.

Q: What belongs in CI for a Karate mock suite?

Pin the Karate dependency or CLI version, start the double within the job, run the consuming tests, and always collect the HTML report on failure. Use dynamic ports unless a container network provides stable service names. Add a syntax or dry-run stage for fast feedback, followed by the executable contract scenarios.

9. Debugging and security interview questions

Q: How do you diagnose a client timeout against a Karate mock?

First confirm that the process started and that the client uses the reported host and port. Next check route order, path shape, method, and whether the catch-all responds. A no-match request can look like a network timeout when no fallback Scenario exists.

Q: How should secrets be handled in mock tests?

Use synthetic credentials whenever authentication is not the system under test. If a proxy needs a real test token, inject it from the CI secret store and redact it from logs and reports. Never commit bearer tokens inside feature examples or mirror production cookies in fixture files.

Q: Why should a Karate mock not be exposed publicly?

The mock is designed as a developer test double, not as an internet-hardened application server. It may intentionally return permissive CORS headers, maintain in-memory state, expose diagnostic fixtures, or forward requests. Public exposure increases the risk of data leakage, resource abuse, and proxy misuse.

Q: What changed for Java interop and trust in Karate v2 mocks?

Incoming request data is inert by default, so Karate expressions embedded in bodies, headers, or parameters are not evaluated. type` is disabled in the default mock trust boundary, which reduces the impact of untrusted payloads. A trusted setup can opt into broader capabilities, but that decision should be narrow and documented.

10. Advanced karate mock server interview questions

Q: When would you choose a JavaScript handler over a feature-file mock?

A JavaScript handler can be cleaner for dense branching, direct request and response object manipulation, or a larger stateful model. body`. Feature files remain easier for mixed QA and product teams to review as executable HTTP examples.

Q: What are beforeScenario and afterScenario useful for in mocks?

Configure beforeScenario for logic that must run once per incoming request, such as incrementing a hit metric or initializing request-scoped context. Configure afterScenario to derive final metadata or record safe diagnostics after route execution. Mock Background is startup-only, so it cannot replace per-request hooks.

Q: Can Karate mocks handle multipart requests and cookies?

Feature mocks expose multipart data through requestParts and cookies through requestCookies. Use those structures when filename, media type, part name, or session identity changes the response. Avoid storing real uploaded documents in a long-lived shared mock state.

Q: When should you not use a Karate mock server?

Do not use it to prove the provider is deployed, network policies are correct, a database migration succeeded, or a third party still honors its live SLA. It also becomes a poor fit when simulation logic approaches the complexity of the production service. Keep real integration, end-to-end, security, and performance checks at the appropriate layers. Compare alternatives in the WireMock stubbing guide and Postman mock server guide before standardizing.

Interview Questions and Answers

These scenario questions test whether you can combine the APIs above into an operating strategy, rather than recite isolated keywords.

Q: Design a mock for an order that becomes complete after two polls. What would you implement?

Store a poll count keyed by order ID in Background state. Return PROCESSING on the first two GET requests and COMPLETE on the third, while keeping the response schema constant. Start a fresh server per test so another poller cannot advance the sequence.

Q: A client sends POST instead of PUT, but the mock still returns success. What is wrong?

The route probably matches only the path and omits methodIs('put'), or a permissive fallback returns 200. Constrain the intended route by method and make the catch-all return a structured 404 or 405. Add a negative consumer request proving POST is rejected.

Q: Tests pass against the mock but fail against production because of a new required header. How do you respond?

Update the authoritative contract first, then change the mock route to reject requests without the header. Add provider-side or real-environment verification so future header changes are detected before release. Review existing fixtures for other lenient assumptions rather than patching only the failing scenario.

Q: How would you introduce controlled chaos with a Karate mock?

Define explicit routes for 500, 429, delayed response, malformed optional data, and connection timeout behavior. Select the fault through a test-only path, header, or isolated server configuration so cases remain deterministic. Assert the consumer's retry, fallback, telemetry, and user-visible outcome for each category.

Q: How would you maintain mocks used by several consumer teams?

Version the shared contract and fixtures, identify a provider owner, and require compatibility evidence for behavioral changes. Keep each route small, publish change notes, and give consumers a migration window for breaking versions. Run a core conformance pack against both the mock and a real test provider.

How Interviewers Grade Your Answers

Signal Strong evidence Weak evidence
Correctness Names real variables and explains first-match routing Invents annotations or Spring-style controllers
Test design Connects each fixture to a consumer risk Builds endpoints without observable assertions
Isolation Uses dynamic ports and owned state Relies on global fixed ports and execution order
Contract judgment Verifies mock behavior against provider evidence Assumes a detailed mock cannot drift
Failure modeling Distinguishes HTTP errors, delay, and no response Returns 200 with an error string for every case
Security Keeps the server private and redacts secrets Treats a mock as safe to expose because it is temporary
Communication Gives a direct answer, example, and trade-off Recites keywords without explaining consequences

For a senior answer, state the consumer risk first, name the smallest mock behavior that exposes it, and explain what still requires a real provider. Interviewers often follow syntax questions with ownership, parallelism, drift, and diagnostics because those concerns determine whether the suite survives beyond a demo. Use the API testing interview questions guide for adjacent HTTP and automation practice, then rehearse in the /practice workspace.

Common Mistakes

  • Putting /users/{id} before /users/admin and wondering why the special fixture never runs.
  • Matching only a path, which allows the wrong HTTP method to receive a successful response.
  • Omitting a catch-all, turning an unmatched request into a slow timeout instead of an actionable 404.
  • Hard-coding port 8080 in parallel CI while the server actually selected a random port.
  • Treating mock Background as per-request setup and accidentally preserving mutable data.
  • Returning friendly payloads that do not match the provider's status, headers, or error schema.
  • Adding realistic domain logic that nobody verifies and the provider never approved.
  • Sharing stateful servers across tests without unique namespaces or lifecycle ownership.
  • Using long delays that inflate the suite when a short timeout boundary would prove the same policy.
  • Proxying arbitrary hosts or publishing injected tokens in request reports.
  • Claiming the mock proves integration, deployment, security controls, or provider performance.
  • Updating a fixture after production changes without adding a compatibility check.

Maintain fixtures like test code: review them, keep data minimal, and delete routes that no longer cover a consumer decision. Use API test data management practices when shared fixtures start acquiring ownership, privacy, or reset problems.

Conclusion

The best answers to karate mock server interview questions combine accurate v2 syntax with boundaries. Explain first-match routing, request helpers, response variables, startup, state, faults, proxy mode, and cleanup, then say what evidence prevents the double from drifting away from its provider.

Run the catalog example, change one route, and predict the consumer failure before executing it. That loop builds the kind of debugging and design fluency an interviewer can distinguish from memorized definitions.

Interview Questions and Answers

How does Karate select a mock Scenario?

Karate evaluates Scenario expressions from top to bottom for each request. The first expression that returns true handles the exchange. Put exact routes first, parameterized routes later, and an empty catch-all Scenario last.

What variables control a Karate mock response?

Use `response` for the body, `responseStatus` for the code, `responseStatusText` for an optional reason, `responseHeaders` for headers, and `responseDelay` for latency. These values let the double represent both successful and negative HTTP contracts.

How do you read a path parameter in a Karate mock?

Match a pattern such as `pathMatches('/orders/{id}')`, then read `pathParams.id`. Combine the path predicate with `methodIs()` so another HTTP verb cannot accidentally use the same fixture.

Why use a random port for an embedded mock?

A random available port prevents clashes across developers, CI workers, and parallel forks. Build the base URL from the server object's `port` property, and never duplicate an assumed port in consumer configuration.

How do stateful Karate mocks work?

Variables initialized in a mock Background persist because that Background runs once at startup. Routes can update maps or counters across requests. Isolate the server per test or namespace data when parallel execution could create collisions.

How do you create a fallback route?

Add an empty Scenario as the last route and return a structured 404. It catches any request that did not satisfy an earlier expression and converts a possible timeout into clear diagnostic evidence.

What is selective proxying in Karate?

Specific routes return synthetic responses, while a later general route calls `karate.proceed()` to forward remaining traffic to a real backend. It is useful for injecting one edge case without copying an entire service.

How do you test a client timeout with a Karate mock?

Set `responseDelay` just beyond a deliberately short client read timeout and assert the client's timeout handling. Use a fast control route to prove the server is healthy, and keep timing tolerances realistic for CI scheduling.

How do you prevent mock drift?

Base fixtures on reviewed contracts or provider examples and run a compatibility subset against the real provider. Version changes, name an owner, and require provider evidence when response behavior changes.

When should you use a JavaScript mock handler?

Use one when dense branching, direct header mutation, or a larger stateful model is clearer in JavaScript. Feature-file mocks remain preferable when executable examples and cross-role readability matter most.

What security boundary applies to Karate mocks?

Treat them as trusted developer tools on local or controlled CI networks. Do not expose them publicly, do not commit secrets, and constrain proxy destinations. Karate v2 also treats incoming request data as inert and disables Java interop by default in mocks.

What distinguishes a senior answer about Karate mocking?

A senior candidate ties each mock behavior to a consumer risk, explains isolation and diagnostics, and identifies what still needs a real provider. They discuss contract drift, lifecycle ownership, concurrency, and security alongside the routing syntax.

Frequently Asked Questions

What is a Karate mock server?

It is an HTTP test double defined with a Karate feature file or a Karate v2 JavaScript handler. It matches real requests and returns controlled bodies, statuses, headers, or delays for local and CI testing.

How do you start a Karate mock server?

Use `karate.start('mock.feature')` inside a Karate test, the `MockServer` Java API in a JUnit fixture, or `karate mock -m mock.feature -p 8080` for a standalone process. Embedded tests should normally use the random port returned by the server object.

Does Karate mock server Background run before every request?

No. In a mock feature, Background runs once when the server starts, so its variables can persist across requests. Use per-request hooks for logic that must execute on every incoming exchange.

How do you return a custom status from a Karate mock?

Set `responseStatus` to the required HTTP code and set `response` to the corresponding body. You can also supply `responseHeaders`, `responseStatusText`, and `responseDelay` when the contract requires them.

Can Karate simulate slow or timed-out APIs?

Yes. Set `responseDelay` for a controlled slow response, or use abort behavior when the client must experience no HTTP reply. Keep client timeouts and test delays short so the case is deterministic and fast.

Can Karate forward requests to a real backend?

Yes. `karate.proceed()` forwards the current request and makes the backend response available for pass-through or controlled modification. Put specific stub routes before a general proxy route.

Is a Karate mock server safe to expose on the internet?

No. It is a developer testing tool, not a hardened public application server. Keep it on a workstation or trusted CI network and restrict any forwarding target.

How do you avoid Karate mock server port conflicts?

Let the embedded server select port 0 and build the client URL from `mock.port`. This isolates concurrent local and CI runs without a shared fixed-port convention.

Related Guides