### Create Ktor HttpClient with MockEngineFactory
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This code demonstrates how to create an instance of Ktor's HttpClient using the MockEngineFactory provided by Mocktor. This setup is essential for enabling request mocking in your tests.
```kotlin
import io.ktor.client.*
import io.paoloconte.mocktor.MockEngineFactory
import io.paoloconte.mocktor.MockEngine
val client = HttpClient(MockEngineFactory)
```
--------------------------------
### Mock GET Requests with Mocktor
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Register a handler for GET requests using MockEngine.get(). This allows you to define specific paths to match and configure the mocked response, including status code, content type, and body. The example demonstrates mocking a request to '/api/users' and returning a JSON response.
```kotlin
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
import io.paoloconte.mocktor.MockEngineFactory
val client = HttpClient(MockEngineFactory)
// Mock a GET request with path and JSON response
MockEngine.get("/api/users") {
response {
status(HttpStatusCode.OK)
contentType(ContentType.Application.Json)
body("{\"users\": [{\"id\": 1, \"name\": \"John\"}]}")
}
}
// Make the request
val response = client.get("http://localhost/api/users")
// response.status == HttpStatusCode.OK
// response.bodyAsText() == "{\"users\": [{\"id\": 1, \"name\": \"John\"}]}"
```
--------------------------------
### Use Fluent Value Matchers for Path, Method, and Headers
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This example showcases Mocktor's fluent value matchers like `equalTo`, `like`, `containing`, and their negations. These matchers can be applied to various request attributes including path, method, query parameters, headers, and form body fields.
```kotlin
// Exact match
path equalTo "/api/users"
// Negated match
path notEqualTo "/api/admin"
// Regex matching
path like "/api/users/[0-9]+"
path notLike "/api/internal/.*"
// Substring matching
path containing "/users/"
path notContaining "/admin/"
```
--------------------------------
### Request Body Matching in Kotlin
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Provides examples of matching POST/PUT/PATCH requests by their body content using Mocktor. It supports exact matching, substring containment, regex patterns, and case-insensitive matching.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
// Exact body match
MockEngine.post("/api/users") {
request {
body equalTo "{\"name\": \"John\", \"age\": 30}"
}
response {
status(HttpStatusCode.Created)
body(
```
--------------------------------
### Define Dynamic Mock Response Based on Request Data
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This example shows how to create a dynamic mock response where the response body is generated based on data from the incoming request, such as query parameters. This allows for more flexible testing scenarios.
```kotlin
MockEngine.get("/api/users") {
response {
contentType(ContentType.Application.Json)
body { request ->
"{\"name\": \"${request.url.parameters["name"]}\"}".toByteArray()
}
}
}
```
--------------------------------
### Define Mock Responses for GET and POST Requests
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This snippet illustrates how to define mock responses for HTTP GET and POST requests using Mocktor's DSL. It shows how to set the status code and response body for specific endpoints.
```kotlin
// Mock a GET request
MockEngine.get("/api/users") {
response {
status(HttpStatusCode.OK)
body("{\"users\": []}")
}
}
// Mock a POST request
MockEngine.post("/api/users") {
response {
status(HttpStatusCode.Created)
body("{\"id\": 1}")
}
}
```
--------------------------------
### Match Request Body Containing a Substring with Mocktor
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This example shows how to use Mocktor to match a request body that contains a specific substring. It also demonstrates how to perform case-insensitive matching.
```kotlin
MockEngine.post("/api/users") {
request {
body containing "\"name\""
}
}
// Case-insensitive matching
MockEngine.post("/api/users") {
request {
body containing "\"NAME\"" ignoreCase true
}
}
```
--------------------------------
### Setting Response Content Type in Kotlin
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This code shows how to set the `Content-Type` header for a mock response in Kotlin Mocktor. It demonstrates setting the content type to `Application.Xml` for a GET request.
```kotlin
MockEngine.get("/api/data") {
response {
status(HttpStatusCode.OK)
contentType(ContentType.Application.Xml)
body("")
}
}
```
--------------------------------
### Mock POST Requests with Mocktor
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Configure mock responses for POST requests using MockEngine.post(). You can specify the path, expected status codes, and the response body. This example shows mocking a POST request to '/api/users' and returning a 'Created' status with a JSON body.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
// Mock a POST request with Created status
MockEngine.post("/api/users") {
response {
status(HttpStatusCode.Created)
body("{\"id\": 1, \"created\": true}")
}
}
// Client request
val response = client.post("http://localhost/api/users") {
contentType(ContentType.Application.Json)
setBody("{\"name\": \"John\", \"email\": \"john@example.com\"}")
}
// response.status == HttpStatusCode.Created
```
--------------------------------
### Implement Custom Content Matchers for Request Body Comparison in Kotlin
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
This example illustrates how to create and use custom content matchers in Mocktor for advanced request body validation. It defines a `CaseInsensitiveMatcher` that compares the request body against an expected byte array, ignoring case differences. This custom matcher implements the `ContentMatcher` interface and is then registered with a handler using `withBodyMatcher`.
```kotlin
import io.paoloconte.mocktor.MockEngine
import io.paoloconte.mocktor.MatchResult
import io.paoloconte.mocktor.contentMatchers.ContentMatcher
import io.ktor.http.*
// Custom matcher that compares body case-insensitively
class CaseInsensitiveMatcher(private val expected: ByteArray) : ContentMatcher {
override fun matches(body: ByteArray): MatchResult {
val bodyString = body.decodeToString().lowercase()
val expectedString = expected.decodeToString().lowercase()
return if (bodyString == expectedString)
MatchResult.Match
else
MatchResult.Mismatch("Body mismatch: expected '$expectedString' but got '$bodyString'")
}
}
MockEngine.post("/api/data") {
request {
withBodyMatcher(CaseInsensitiveMatcher("HELLO WORLD".toByteArray()))
}
response {
status(HttpStatusCode.OK)
}
}
// This request will match because "hello world" equals "HELLO WORLD" case-insensitively
// client.post("/api/data") {
// setBody("hello world")
// }
```
--------------------------------
### Clear Handlers and Requests Between Tests (Kotlin)
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
Demonstrates how to clear all registered handlers and recorded requests using `MockEngine.clear()`. This method should typically be called in a test setup or teardown phase (e.g., `@AfterTest`) to ensure tests are isolated and do not interfere with each other.
```kotlin
@AfterTest
fun tearDown() {
MockEngine.clear()
}
```
--------------------------------
### Path Matching with Regex and Substring in Kotlin
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Demonstrates how to match request paths using exact values, regex patterns, or substring containment with Mocktor's fluent DSL. This allows for flexible routing of mock responses.
```kotlin
import io.paoloconte.mocktor.MockEngine
// Exact path match (default)
MockEngine.get("/api/users") {
response { body("exact match") }
}
// Regex pattern matching for dynamic paths
MockEngine.get {
request {
path like "/api/users/[0-9]+"
}
response { body("matched user ID path") }
}
// Negative regex matching
MockEngine.get {
request {
path notLike "/api/admin/.*"
}
response { body("not admin path") }
}
// Substring matching
MockEngine.get {
request {
path containing "/users/"
}
response { body("contains users") }
}
// Negative substring matching
MockEngine.get {
request {
path notContaining "/internal/"
}
response { body("not internal path") }
}
```
--------------------------------
### Verify HTTP Requests with Query Parameters (Kotlin)
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
Illustrates how to verify HTTP requests by checking their query parameters using MockEngine. This is essential for testing endpoints that accept various query parameters to filter or paginate results. The verification ensures the correct path and specific query parameter key-value pairs are present.
```kotlin
client.get("http://localhost/api/users?page=1&limit=10")
MockEngine.verify(count = 1) {
path equalTo "/api/users"
queryParams have "page" equalTo "1"
queryParams have "limit" equalTo "10"
}
```
--------------------------------
### Query Parameter Matching in Kotlin
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Shows how to match requests by query parameters using Mocktor's fluent DSL. It supports strict matching and ignoring specific parameters, allowing for precise control over mock responses.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
// Match specific query parameters (extra params are ignored by default)
MockEngine.get("/api/users") {
request {
queryParams have "page" equalTo "1"
queryParams have "limit" equalTo "10"
}
response {
status(HttpStatusCode.OK)
body(
```
--------------------------------
### Host Matching in Kotlin
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Illustrates how to match requests based on the target host using Mocktor. This is useful for mocking different backends or services that respond to the same path but different hosts.
```kotlin
import io.paoloconte.mocktor.MockEngine
// Match requests to a specific host
MockEngine.get {
request {
host equalTo "api.example.com"
path equalTo "/users"
}
response { body("from api.example.com") }
}
// Different response for different host
MockEngine.get {
request {
host equalTo "staging.example.com"
path equalTo "/users"
}
response { body("from staging") }
}
```
--------------------------------
### Match Requests by Query Parameters with Mocktor
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This snippet shows how to match incoming HTTP requests based on their query parameters using Mocktor's fluent DSL. It covers matching specific parameters and their values, and also demonstrates how to handle exact parameter matching with `strictQueryParams()`.
```kotlin
MockEngine.get("/api/users") {
request {
queryParams have "page" equalTo "1"
queryParams have "limit" equalTo "10"
}
response {
status(HttpStatusCode.OK)
body("{\"users\": [], \"page\": 1}")
}
}
// Matches: GET /api/users?page=1&limit=10
// Matches: GET /api/users?limit=10&page=1 (order doesn't matter)
// Example with strict query parameters
MockEngine.get("/api/users") {
request {
queryParams have "page" equalTo "1"
queryParams ignore "timestamp"
strictQueryParams() // Fail if request has extra params
}
...
}
```
--------------------------------
### Verify HTTP Requests with MockEngine (Kotlin)
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
Demonstrates how to verify that specific HTTP requests were made during a test using MockEngine. It covers verifying the exact count of requests, ensuring at least one request was made, and confirming no requests were made. All requests are recorded regardless of whether they match a handler.
```kotlin
// Make some requests
client.post("http://localhost/api/bookings")
client.post("http://localhost/api/bookings")
// Verify exact count
MockEngine.verify(count = 2) {
method equalTo HttpMethod.Post
path equalTo "/api/bookings"
}
// Verify at least one request was made (no count = at least 1)
MockEngine.verify {
method equalTo HttpMethod.Get
path equalTo "/api/users"
}
// Verify no requests were made
MockEngine.verify(count = 0) {
method equalTo HttpMethod.Delete
}
```
--------------------------------
### Match Requests by Path using Mocktor DSL
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This code demonstrates different ways to match requests based on their URL path using Mocktor. It covers exact path matching, regex pattern matching, and substring matching, both directly and through the request DSL.
```kotlin
// Exact path match
MockEngine.get("/api/users") { ... }
// Or using the DSL
MockEngine.get {
request {
path equalTo "/api/users"
}
...
}
// Regex pattern matching
MockEngine.get {
request {
path like "/api/users/[0-9]+"
}
response {
status(HttpStatusCode.OK)
}
}
// Substring matching
MockEngine.get {
request {
path containing "/users/"
}
...
}
```
--------------------------------
### Verify HTTP Requests with Headers (Kotlin)
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
Shows how to verify HTTP requests made to MockEngine, specifically checking for the presence and value of request headers. This is crucial for testing endpoints that rely on authentication tokens or other header-based information. The verification includes matching the path and the specific header.
```kotlin
client.get("http://localhost/api/users") {
header("Authorization", "Bearer token123")
}
MockEngine.verify(count = 1) {
path equalTo "/api/users"
headers have "Authorization" equalTo "Bearer token123"
}
```
--------------------------------
### Match Requests by Headers in Kotlin
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This snippet demonstrates how to match incoming requests based on their headers using Kotlin Mocktor. It shows how to check for the presence and specific values of headers like 'Authorization' and 'Accept'.
```kotlin
MockEngine.get("/api/users") {
request {
headers have "Authorization" equalTo "Bearer token123"
headers have "Accept" containing "application/json"
}
response {
status(HttpStatusCode.OK)
}
}
```
```kotlin
MockEngine.get("/api/users") {
request {
headers dontHave "X-Custom-Header" equalTo "forbidden-value"
}
...
}
```
--------------------------------
### Simulate Stateful Interactions with State-Based Request Matching in Kotlin
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
This snippet demonstrates how to simulate stateful interactions, such as authentication flows, using state-based handler matching in Mocktor. It defines handlers that only match when the MockEngine is in a specific state, allowing for sequential logic simulation. The `withState` function specifies the required state, and `setState` transitions the engine to a new state upon successful matching.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
import io.paoloconte.mocktor.MockEngine.INITIAL_STATE
MockEngine.clear()
// Handler matches only in INITIAL_STATE (default)
MockEngine.get("/login") {
withState(INITIAL_STATE)
response {
status(HttpStatusCode.OK)
body("Login successful")
setState("LOGGED_IN") // Transition to new state
}
}
// Handler matches only in LOGGED_IN state
MockEngine.get("/profile") {
withState("LOGGED_IN")
response {
status(HttpStatusCode.OK)
body("User Profile Data")
}
}
// Handler for logout, transitions back to INITIAL_STATE
MockEngine.get("/logout") {
withState("LOGGED_IN")
response {
status(HttpStatusCode.OK)
body("Logout successful")
setState(INITIAL_STATE)
}
}
// Test the flow:
// MockEngine.state == INITIAL_STATE
// 1. /profile fails (404) because state is INITIAL
// val profileBefore = client.get("http://localhost/profile")
// profileBefore.status == HttpStatusCode.NotFound
// 2. /login succeeds and changes state to LOGGED_IN
// val login = client.get("http://localhost/login")
// login.status == HttpStatusCode.OK
// MockEngine.state == "LOGGED_IN"
// 3. /profile now succeeds
// val profileAfter = client.get("http://localhost/profile")
// profileAfter.status == HttpStatusCode.OK
```
--------------------------------
### Load Request/Response Bodies from Resource Files
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Load request expectations and response bodies from classpath resource files for cleaner test code. Supports generic resource loading, JSON, and XML matching.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
import io.paoloconte.mocktor.json.equalToJsonResource
import io.paoloconte.mocktor.xml.equalToXmlResource
// Load expected body and response from resource files
MockEngine.post("/api/users") {
request {
body equalToResource "/fixtures/request.json"
}
response {
status(HttpStatusCode.Created)
bodyFromResource("/fixtures/response.json")
}
}
// Semantic JSON matching from resource file
MockEngine.post("/api/orders") {
request {
body equalToJsonResource "/fixtures/order-request.json"
}
response { status(HttpStatusCode.Created) }
}
// Semantic XML matching from resource file
MockEngine.post("/api/data") {
request {
body equalToXmlResource "/fixtures/request.xml"
}
response { status(HttpStatusCode.OK) }
}
```
--------------------------------
### State Management for Stateful Interactions (Kotlin)
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
Enables state-based request matching in MockEngine, simulating stateful interactions like authentication flows. Handlers can be configured to match only when the engine is in a specific state, and responses can transition the engine to a new state. This is crucial for testing complex, multi-step API interactions.
```kotlin
// Handler matches only if engine state is "INITIAL_STATE" (default)
MockEngine.post("/login") {
withState(MockEngine.INITIAL_STATE)
response {
status(HttpStatusCode.OK)
setState("LOGGED_IN") // Transition to new state
}
}
// Handler matches only if engine state is "LOGGED_IN"
MockEngine.get("/profile") {
withState("LOGGED_IN")
response {
status(HttpStatusCode.OK)
body("User Profile")
}
}
```
--------------------------------
### Match Any HTTP Method with Mocktor's on()
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Use the generic MockEngine.on() function to register handlers that match any HTTP method or custom methods. This provides flexibility for scenarios where the HTTP method might vary or when dealing with non-standard methods. You can specify the path and optionally the HttpMethod.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
// Match any HTTP method on a specific path
MockEngine.on(path = "/api/data") {
response {
status(HttpStatusCode.OK)
body("{\"any\": true}")
}
}
// Match a custom HTTP method
MockEngine.on(HttpMethod("CUSTOM"), "/api/special") {
response {
status(HttpStatusCode.OK)
body("{\"method\": \"custom\"}")
}
}
// Match specific method using on()
MockEngine.on(HttpMethod.Post, "/api/users") {
response {
status(HttpStatusCode.Created)
body("{\"id\": 1}")
}
}
```
--------------------------------
### Loading Request and Response Body from Resources in Kotlin
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This snippet demonstrates loading request and response bodies from classpath resource files in Kotlin Mocktor. It uses `equalToResource` for request bodies and `bodyFromResource` for response bodies.
```kotlin
MockEngine.post("/api/users") {
request {
body equalToResource "/fixtures/request.json"
}
response {
bodyFromResource("/fixtures/response.json")
}
}
```
--------------------------------
### Verify HTTP Request Counts and Details
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Verify that specific HTTP requests were made during a test using MockEngine.verify(). Supports verification by method, path, headers, and query parameters.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
// Make some requests
client.post("http://localhost/api/bookings")
client.post("http://localhost/api/bookings")
client.get("http://localhost/api/users")
// Verify exact count
MockEngine.verify(count = 2) {
method equalTo HttpMethod.Post
path equalTo "/api/bookings"
}
// Verify at least one request was made (no count = at least 1)
MockEngine.verify {
method equalTo HttpMethod.Get
path equalTo "/api/users"
}
// Verify no requests were made
MockEngine.verify(count = 0) {
method equalTo HttpMethod.Delete
}
// Verify with headers
client.get("http://localhost/api/protected") {
header("Authorization", "Bearer token123")
}
MockEngine.verify(count = 1) {
path equalTo "/api/protected"
headers have "Authorization" equalTo "Bearer token123"
}
// Verify with query parameters
client.get("http://localhost/api/users?page=1&limit=10")
MockEngine.verify(count = 1) {
path equalTo "/api/users"
queryParams have "page" equalTo "1"
queryParams have "limit" equalTo "10"
}
```
--------------------------------
### XML Content Matching in Kotlin
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This snippet illustrates semantic XML comparison in Kotlin Mocktor, ignoring whitespace and comments. It uses the `equalToXml` matcher for matching request bodies against expected XML structures.
```kotlin
import io.paoloconte.mocktor.xml.equalToXml
MockEngine.post("/api/data") {
request {
body equalToXml "- value
"
}
response {
status(HttpStatusCode.OK)
}
}
// This request will match even with different formatting:
client.post("/api/data") {
setBody("""
- value
""")
}
```
--------------------------------
### Load XML Body from Resources with Semantic Comparison (Kotlin)
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
Uses `equalToXmlResource` to load an XML body from a resource file for semantic comparison. This allows for matching requests even if they have different whitespace than the resource file. It's useful for testing API endpoints that expect specific XML payloads.
```kotlin
import io.paoloconte.mocktor.xml.equalToXmlResource
MockEngine.post("/api/data") {
request {
body equalToXmlResource "/fixtures/request.xml"
}
response {
status(HttpStatusCode.OK)
}
}
// Matches even if request has different whitespace than the resource file
```
--------------------------------
### Access Recorded Requests Directly (Kotlin)
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
Provides a way to directly access all recorded HTTP requests made during a test session using MockEngine. This allows for detailed inspection of request methods, URLs, and other properties, enabling more granular assertions and debugging. It's useful when standard verification methods are insufficient.
```kotlin
val requests = MockEngine.requests()
assertEquals(2, requests.size)
assertEquals(HttpMethod.Post, requests[0].request.method)
assertEquals("/api/users", requests[0].request.url.encodedPath)
```
--------------------------------
### Mock PUT, DELETE, PATCH, HEAD Requests with Mocktor
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Mocktor supports mocking PUT, DELETE, PATCH, and HEAD requests using dedicated functions like MockEngine.put(), MockEngine.delete(), MockEngine.patch(), and MockEngine.head(). The DSL syntax for defining responses remains consistent across these methods, allowing you to specify status codes, headers, and bodies.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
// Mock PUT request
MockEngine.put("/api/users/1") {
response {
status(HttpStatusCode.OK)
body("{\"updated\": true}")
}
}
// Mock DELETE request
MockEngine.delete("/api/users/1") {
response {
status(HttpStatusCode.NoContent)
}
}
// Mock PATCH request
MockEngine.patch("/api/users/1") {
response {
status(HttpStatusCode.OK)
body("{\"patched\": true}")
}
}
// Mock HEAD request
MockEngine.head("/api/users") {
response {
status(HttpStatusCode.OK)
header("X-Total-Count", "42")
}
}
```
--------------------------------
### Custom Request Matching
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Use the `matching` function for arbitrary request validation with full access to the request object. This allows for complex conditions on query parameters, headers, or the request body.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
import io.paoloconte.mocktor.bodyAsString
// Custom validation on query parameters
MockEngine.get("/api/users") {
request {
matching { request ->
request.url.parameters["id"]?.toIntOrNull() in 1..100
}
}
response {
status(HttpStatusCode.OK)
body(
```
--------------------------------
### XML Content Matching
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Use semantic XML comparison that ignores whitespace and formatting differences using the XML matcher module. This is useful for testing endpoints that process XML data.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
import io.paoloconte.mocktor.xml.equalToXml
// Semantic XML matching
MockEngine.post("/api/data") {
request {
body equalToXml "- value
"
}
response {
status(HttpStatusCode.OK)
contentType(ContentType.Application.Xml)
body("true")
}
}
// This request will match even with different formatting:
client.post("/api/data") {
setBody("""
- value
""")
}
```
--------------------------------
### Access All Recorded HTTP Requests
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Access all recorded HTTP calls directly using MockEngine.requests() for custom assertions and detailed inspection. This allows for programmatic analysis of the mock interactions.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
client.get("http://localhost/api/users?page=1")
client.post("http://localhost/api/users") {
setBody("{\"name\": \"John\"}")
}
val requests = MockEngine.requests()
// requests.size == 2
// Inspect first request
val firstRequest = requests[0].request
// firstRequest.method == HttpMethod.Get
// firstRequest.url.encodedPath == "/api/users"
// firstRequest.url.parameters["page"] == "1"
// Inspect second request
val secondRequest = requests[1].request
// secondRequest.method == HttpMethod.Post
// secondRequest.url.encodedPath == "/api/users"
```
--------------------------------
### Implement CaseInsensitiveMatcher for Request Body
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This snippet shows how to implement the ContentMatcher interface to create a custom matcher that compares request bodies case-insensitively. It defines a CaseInsensitiveMatcher class and demonstrates its usage with MockEngine.post to mock an API endpoint.
```kotlin
import io.paoloconte.mocktor.contentMatchers.ContentMatcher
import io.paoloconte.mocktor.MatchResult
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.HttpStatusCode
import io.paoloconte.mocktor.engine.MockEngine
// Custom matcher that compares body case-insensitively
class CaseInsensitiveMatcher(private val expected: ByteArray) : ContentMatcher {
override fun matches(body: ByteArray): MatchResult {
val bodyString = body.decodeToString().lowercase()
val expectedString = expected.decodeToString().lowercase()
return if (bodyString == expectedString)
MatchResult.Match
else
MatchResult.Mismatch("Body mismatch: expected '$expectedString' but got '$bodyString'")
}
}
// Mocking an API endpoint with the custom matcher
MockEngine.post("/api/data") {
request {
withBodyMatcher(CaseInsensitiveMatcher("HELLO WORLD".toByteArray()))
}
response {
status(HttpStatusCode.OK)
}
}
// Example of a client request that will match
// Assuming 'client' is an instance of Ktor HttpClient
// client.post("/api/data") {
// setBody("hello world")
// }
```
--------------------------------
### JSON Content Matching in Kotlin
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This code demonstrates semantic JSON comparison in Kotlin Mocktor, ignoring key ordering and whitespace. It uses the `equalToJson` matcher for matching request bodies against expected JSON structures.
```kotlin
import io.paoloconte.mocktor.json.equalToJson
MockEngine.post("/api/users") {
request {
body equalToJson """{"name": "John", "age": 30}"""
}
response {
status(HttpStatusCode.Created)
}
}
// This request will match even with different key order:
client.post("/api/users") {
setBody("""{"age": 30, "name": "John"}""")
}
```
--------------------------------
### Loading JSON Body from Resources in Kotlin
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This code shows how to load JSON request bodies from resource files using `equalToJsonResource` in Kotlin Mocktor. This method performs semantic JSON comparison, ignoring key order and whitespace.
```kotlin
import io.paoloconte.mocktor.json.equalToJsonResource
MockEngine.post("/api/users") {
request {
body equalToJsonResource "/fixtures/request.json"
}
response {
status(HttpStatusCode.Created)
}
}
// Matches even if request has different key order than the resource file
```
--------------------------------
### Match Request Body with Regex and Negative Matchers
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This snippet illustrates how to use regular expressions with Mocktor's `like` and `notLike` matchers to validate request body content. This provides powerful pattern matching capabilities for request bodies.
```kotlin
MockEngine.post("/api/users") {
request {
body like ".*\"name\":\"[A-Za-z]+\".*"
}
}
// Negative match
MockEngine.post("/api/users") {
request {
body notLike ".*\"admin\".*"
}
}
```
--------------------------------
### Add Mocktor Dependencies to build.gradle.kts
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This snippet shows how to add the necessary Mocktor dependencies to your Kotlin project's build.gradle.kts file. It includes the core Mocktor library and optional dependencies for JSON and XML body matching.
```kotlin
dependencies {
testImplementation("io.paoloconte:mocktor:2.1.2")
// Optional: JSON body matching
testImplementation("io.paoloconte:mocktor-json:2.1.2")
// Optional: XML body matching
testImplementation("io.paoloconte:mocktor-xml:2.1.2")
}
```
--------------------------------
### Generate Dynamic Responses Based on Request Data
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Generate response content dynamically based on request data using a lambda function. This allows for flexible mock responses that adapt to incoming request parameters.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
// Dynamic response using request data
MockEngine.get("/api/users") {
response {
contentType(ContentType.Application.Json)
body { request ->
val name = request.url.parameters["name"] ?: "Unknown"
val id = request.url.parameters["id"] ?: "0"
"""{"id": $id, "name": "$name"}""".toByteArray()
}
}
}
// Response: {"id": 42, "name": "John"} for GET /api/users?id=42&name=John
```
--------------------------------
### Match Exact Request Body Content with Mocktor
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This code snippet demonstrates how to configure Mocktor to match a POST request based on its exact body content. This is useful for testing APIs that require specific data structures in the request body.
```kotlin
MockEngine.post("/api/users") {
request {
body equalTo "{\"name\": \"John\"}"
}
response {
status(HttpStatusCode.Created)
}
}
```
--------------------------------
### Custom Request Matching with Lambda in Kotlin
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This snippet shows how to use the `matching` block in Kotlin Mocktor for custom request validation. It allows defining complex matching logic using lambda expressions, including checking URL parameters and request body content.
```kotlin
MockEngine.get("/api/users") {
request {
matching { request ->
request.url.parameters["id"]?.toIntOrNull() in 1..100
}
}
response {
status(HttpStatusCode.OK)
body("{\"id\": 123, \"name\": \"John\"}")
}
}
```
```kotlin
MockEngine.post("/api/users") {
request {
matching { request ->
val body = request.bodyAsString()
body.contains("\"role\":\"admin\"")
}
}
response {
status(HttpStatusCode.OK)
}
}
```
--------------------------------
### Ignoring Unknown Keys in JSON Matching in Kotlin
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This code demonstrates how to ignore extra keys in the request body that are not present in the expected JSON structure when using Kotlin Mocktor. The `ignoreUnknownKeys` option provides flexibility in matching requests with additional fields.
```kotlin
MockEngine.post("/api/users") {
request {
body equalToJson """{"name": "John"}""" ignoreUnknownKeys true
}
response {
status(HttpStatusCode.Created)
}
}
// This request will match even with extra fields:
client.post("/api/users") {
setBody("""{"name": "John", "age": 30, "extra": "field"}""")
}
```
--------------------------------
### Match Form URL-Encoded Body in Kotlin
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This code illustrates matching form data in POST requests using Kotlin Mocktor's fluent DSL. It covers matching specific form parameters and ignoring others, as well as enforcing strict parameter matching.
```kotlin
MockEngine.post("/api/login") {
request {
formParams have "username" equalTo "john"
formParams have "password" equalTo "secret"
}
response {
status(HttpStatusCode.OK)
}
}
// Matches requests with body: username=john&password=secret
// Parameter order doesn't matter
```
```kotlin
MockEngine.post("/api/data") {
request {
formParams have "name" equalTo "test"
formParams ignore "timestamp"
}
response {
status(HttpStatusCode.OK)
}
}
```
```kotlin
MockEngine.post("/api/login") {
request {
formParams have "username" equalTo "john"
strictFormParams() // Fail if request has extra fields
}
...
}
```
--------------------------------
### Throw Exceptions in Mock Responses
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Configure mock handlers to throw exceptions for testing error handling and retry logic in the client. This simulates network issues or server-side errors.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
import java.io.IOException
import kotlin.test.assertFailsWith
MockEngine.get("/api/unstable") {
response {
throws(IOException("Network error"))
}
}
// Test that client properly handles the exception
val exception = assertFailsWith {
client.get("http://localhost/api/unstable")
}
// exception.message == "Network error"
```
--------------------------------
### Customize Default Response Status Code (Kotlin)
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
Allows customization of the default HTTP status code returned by MockEngine when no handler matches an incoming request. By default, this is `404 Not Found`, but it can be changed to other codes like `BadRequest`. This setting is reset if `clear()` is called.
```kotlin
// Change the default status code for unmatched requests
MockEngine.noMatchStatusCode = HttpStatusCode.BadRequest
This field resets if `clear()` is called.
```
--------------------------------
### Match Form URL-Encoded Body
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Match form data in POST requests with support for strict field matching and ignoring specific fields. This is useful for testing API endpoints that accept form submissions.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
// Match form parameters
MockEngine.post("/api/login") {
request {
formParams have "username" equalTo "john"
formParams have "password" equalTo "secret123"
}
response {
status(HttpStatusCode.OK)
body(
```
--------------------------------
### Set Custom Response Headers
Source: https://context7.com/paoloconte/kotlin-mocktor/llms.txt
Add custom headers to mock responses for testing header-dependent client behavior. This is useful for simulating API behaviors like rate limiting or request tracking.
```kotlin
import io.ktor.http.*
import io.paoloconte.mocktor.MockEngine
MockEngine.get("/api/data") {
response {
status(HttpStatusCode.OK)
contentType(ContentType.Application.Json)
header("X-Request-Id", "abc-123")
header("X-Rate-Limit-Remaining", "99")
header("Cache-Control", "max-age=3600")
body("{\"data\": \"test\"}")
}
}
val response = client.get("http://localhost/api/data")
// response.headers["X-Request-Id"] == "abc-123"
// response.headers["X-Rate-Limit-Remaining"] == "99"
```
--------------------------------
### Ignoring Fields in JSON Matching in Kotlin
Source: https://github.com/paoloconte/kotlin-mocktor/blob/main/README.md
This snippet shows how to ignore specific fields, such as timestamps or IDs, during JSON content matching in Kotlin Mocktor. The `ignoreFields` option allows for flexible matching when certain fields are expected to vary.
```kotlin
MockEngine.post("/api/users") {
request {
body equalToJson """{"name": "John"}""" ignoreFields setOf("createdAt")
}
response {
status(HttpStatusCode.Created)
}
}
// This request will match even with different createdAt value:
client.post("/api/users") {
setBody("""{"name": "John", "createdAt": "2025-12-26"}""")
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.