Karate API Mocking: Mock Servers for Integration Testing
Karate includes a mock server that runs in-process, defined entirely in .feature files. You can start a mock server that responds to HTTP requests, use it to isolate a service under test from its dependencies, and tear it down when the test ends — no external tools or separate processes required.
How Karate Mocks Work
Karate mocks are defined as feature files where each scenario describes a request pattern and the response to return. The mock server evaluates incoming requests against the scenarios in order and returns the first match.
The mock server supports HTTP (and HTTPS), handles JSON and XML, and can return dynamic responses based on request content.
Basic Mock Definition
Create a mock feature file:
# src/test/resources/mocks/payment-service-mock.feature
Feature: Payment Service Mock
Scenario: Health check
Given pathMatches '/health'
And methodIs 'GET'
Then status 200
And def responseBody = { status: 'UP' }
And match response == responseBody
Scenario: Process payment - success
Given pathMatches '/payments'
And methodIs 'POST'
And request.amount < 10000
Then status 200
And def response = { transactionId: '12345', status: 'approved' }
Scenario: Process payment - declined
Given pathMatches '/payments'
And methodIs 'POST'
And request.amount >= 10000
Then status 200
And def response = { transactionId: '12346', status: 'declined', reason: 'limit exceeded' }Key keywords in mock scenarios:
pathMatches— matches the request path (supports wildcards)methodIs— matches HTTP method (case-insensitive)request— the parsed request body, available as a JSON objectdef response— sets the response bodystatus— sets the HTTP status code
Starting the Mock Server in Tests
From Java (JUnit 5)
import com.intuit.karate.http.HttpServer;
class PaymentServiceTest {
static HttpServer mockServer;
@BeforeAll
static void startMock() {
mockServer = MockServer
.feature("classpath:mocks/payment-service-mock.feature")
.http(8081)
.build();
}
@AfterAll
static void stopMock() {
mockServer.stop();
}
@Karate.Test
Karate testPayments() {
return Karate.run("classpath:api/payments.feature")
.systemProperty("payment.service.url", "http://localhost:8081");
}
}From a Karate Feature File
You can also start the mock from within a feature file:
Feature: Payment flow integration test
Background:
* def mockServer = karate.start('classpath:mocks/payment-service-mock.feature', 8081)
* url 'http://localhost:3000' # the service under test
Scenario: Process valid payment
Given path '/checkout'
And request { amount: 5000, currency: 'USD' }
When method POST
Then status 200
And match response.status == 'success'
* karate.stop(mockServer)karate.start() returns a server handle. karate.stop() shuts it down. Both are synchronous.
Dynamic Responses
Mocks can inspect request content and return different responses:
Scenario: Get user by ID
Given pathMatches '/users/{id}'
And methodIs 'GET'
Then status 200
And def userId = pathParams.id
And def response = { id: '#(userId)', name: 'User ' + userId, active: true }pathParams gives you the captured path parameters. The response is built dynamically using the captured value.
Using Request Headers in Mock Responses
Scenario: Authenticated request
Given pathMatches '/protected'
And methodIs 'GET'
And requestHeaders['Authorization'] != null
Then status 200
And def response = { data: 'secret', requestedBy: requestHeaders['Authorization'] }
Scenario: Unauthenticated request
Given pathMatches '/protected'
And methodIs 'GET'
Then status 401
And def response = { error: 'Unauthorized' }Karate evaluates scenarios in order, so the authenticated scenario must come first.
Request Body Matching
Scenario: Create order with items
Given pathMatches '/orders'
And methodIs 'POST'
And request.items.length > 0
Then status 201
And def response = { orderId: 'ORD-001', itemCount: request.items.length }
Scenario: Create order without items
Given pathMatches '/orders'
And methodIs 'POST'
Then status 400
And def response = { error: 'Order must contain at least one item' }request gives you the full parsed request body. You can use any JavaScript expression to match against it.
Responding with Delays
Simulate slow responses to test timeout handling:
Scenario: Slow response
Given pathMatches '/slow-endpoint'
And methodIs 'GET'
Then status 200
* karate.pause(2000)
And def response = { result: 'delayed' }karate.pause(ms) blocks the mock handler for the given duration before returning the response.
Setting Response Headers
Scenario: Response with custom headers
Given pathMatches '/download'
And methodIs 'GET'
Then status 200
And header Content-Type = 'application/octet-stream'
And header Content-Disposition = 'attachment; filename="file.csv"'
And def response = 'id,name\n1,test'Error Scenarios
Scenario: Service unavailable
Given pathMatches '/unstable'
And methodIs 'GET'
Then status 503
And def response = { error: 'Service Unavailable', retryAfter: 30 }Stateful Mocks
Karate mocks can maintain state across requests using karate.set() and karate.get():
Scenario: Create resource
Given pathMatches '/resources'
And methodIs 'POST'
Then status 201
* def id = java.util.UUID.randomUUID() + ''
* karate.set('resource_' + id, request)
And def response = { id: '#(id)' }
Scenario: Get resource
Given pathMatches '/resources/{id}'
And methodIs 'GET'
* def stored = karate.get('resource_' + pathParams.id)
* def exists = stored != null
Then status '#(exists ? 200 : 404)'
And def response = '#(exists ? stored : { error: "Not found" })'This creates an in-memory store scoped to the mock server's lifetime.
Running Mocks as Standalone Servers
For development or manual testing, you can run a Karate mock as a standalone process:
java -jar karate.jar -m mock.feature -p 8081This starts the mock on port 8081 and keeps it running until you kill the process.
Practical Isolation Pattern
The typical integration testing pattern is:
- Start mock servers for all dependencies before the test suite
- Configure the service under test to point at mock URLs (via environment variables or config)
- Run the tests
- Verify that the service called the mocks correctly (optional — Karate mocks don't have built-in call verification, but you can use
karate.get()to check state the mock stored) - Stop the mock servers after the suite
@BeforeAll
static void setup() {
paymentMock = MockServer.feature("classpath:mocks/payment.feature").http(8081).build();
emailMock = MockServer.feature("classpath:mocks/email.feature").http(8082).build();
// Point service under test at mocks
System.setProperty("PAYMENT_SERVICE_URL", "http://localhost:8081");
System.setProperty("EMAIL_SERVICE_URL", "http://localhost:8082");
}
@AfterAll
static void teardown() {
paymentMock.stop();
emailMock.stop();
}Limitations
Karate mocks don't have built-in call verification (unlike Mockito's verify() or WireMock's request journal). If you need to assert that a specific request was made to the mock, you have to implement it yourself via shared state.
HTTPS mocking requires configuring a self-signed certificate. For most integration testing, HTTP is sufficient since the mock runs locally.
The mock server handles requests synchronously. High-concurrency scenarios (many parallel requests) may queue up depending on server capacity.