### cURL Request Example Source: https://www.mock-server.com/mock_server/getting_started Example of how to set up a mock server expectation using cURL. ```APIDOC ## cURL Request Example ### Description Demonstrates setting up a mock server expectation using the cURL command-line tool. ### Method PUT ### Endpoint http://localhost:1080/mockserver/expectation ### Request Body ```json { "httpRequest" : { "body" : { "type" : "JSON", "json" : { "id" : 1, "name" : "A green door", "price" : "${json-unit.ignore-element}", "enabled" : "${json-unit.any-boolean}", "tags" : [ "home", "green" ] } } }, "httpResponse" : { "statusCode" : 202, "body" : "some_response_body" } } ``` ``` -------------------------------- ### Java Client Example Source: https://www.mock-server.com/mock_server/getting_started Example of setting up a mock server expectation using the Java client library. ```APIDOC ## Java Client Example ### Description Provides a Java code snippet for configuring mock server expectations, including matching requests by JSON schema. ### Method Not Applicable (Client-side configuration) ### Endpoint Not Applicable (Client-side configuration) ### Parameters #### Request Body (Implicitly defined in client code) - **jsonSchema** (string) - Defines the JSON schema for matching the request body. ### Request Example ```java new MockServerClient("localhost", 1080) .when( request() .withBody( jsonSchema("{\"$\": \"https://json-schema.org/draft-04/schema#\",\"title\": \"Product\",\"description\": \"A product from Acme catalog\",\"type\": \"object\",\"properties\": {\"id\": {\"description\": \"The unique identifier for a product\",\"type\": \"integer\"},\"name\": {\"description\": \"Name of the product\",\"type\": \"string\"},\"price\": {\"type\": \"number\",\"minimum\": 0,\"exclusiveMinimum\": true},\"tags\": {\"type\": \"array\",\"items\": {\"type\": \"string\"},\"minItems\": 1,\"uniqueItems\": true}}\n }") ) ) .respond( response() .withBody("some_response_body") ); ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message from the mock server. #### Response Example (Response is handled by the mock server based on the expectation) ``` -------------------------------- ### JavaScript Client Example Source: https://www.mock-server.com/mock_server/getting_started Example of setting up a mock server expectation using the JavaScript client library. ```APIDOC ## JavaScript Client Example ### Description Illustrates how to configure mock server expectations using the JavaScript client, including matching requests by JSON schema. ### Method Not Applicable (Client-side configuration) ### Endpoint Not Applicable (Client-side configuration) ### Parameters #### Request Body (Implicitly defined in client code) - **jsonSchema** (object) - Defines the JSON schema for matching the request body. ### Request Example ```javascript var mockServerClient = require('mockserver-client').mockServerClient; mockServerClient("localhost", 1080).mockAnyResponse({ "httpRequest": { "body": { "type": "JSON_SCHEMA", "jsonSchema": { "$schema": "https://json-schema.org/draft-04/schema#", "title": "Product", "description": "A product from Acme catalog", "type": "object", "properties": { "id": { "description": "The unique identifier for a product", "type": "integer" }, "name": { "description": "Name of the product", "type": "string" }, "price": { "type": "number", "minimum": 0, "exclusiveMinimum": true }, "tags": { "type": "array", "items": { "type": "string" }, "minItems": 1, "uniqueItems": true } }, "required": ["id", "name", "price"] } } } }); ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message from the mock server. #### Response Example (Response is handled by the mock server based on the expectation) ``` -------------------------------- ### MockServer Client Examples Source: https://www.mock-server.com/mock_server/getting_started Examples of how to use the MockServer client in JavaScript and Java to set up expectations. ```APIDOC ## MockServer Client Usage ### JavaScript Example ```javascript var mockServerClient = require('mockserver-client').mockServerClient; mockServerClient("localhost", 1080).mockAnyResponse({ "httpRequest": { "path": "/some/path" }, "httpOverrideForwardedRequest": { "httpRequest": { "path": "/some/other/path", "headers": { "Host": ["target.host.com"] } }, "httpResponse": { "body": "some_overridden_body" } } }).then( function () { console.log("expectation created"); }, function (error) { console.log(error); } ); ``` ### Java Example (Forward Overridden Request) ```java new MockServerClient("localhost", 1080) .when( request() .withPath("/some/path") ) .forward( forwardOverriddenRequest( request() .withPath("/some/other/path") .withHeader("Host", "target.host.com"), response() .withBody("some_overridden_body") ) ); ``` ### Java Example (Forward Overridden and Modified Request) ```java new MockServerClient("localhost", 1080) .when( request() .withPath("/some/path") ) .forward( forwardOverriddenRequest( request() // this replaces the entire set of headers .withHeader("Host", "target.host.com") .withBody("some_overridden_body"), requestModifier() .withPath("^/(.+)/(.+$", "/prefix/$1/infix/$2/postfix") .withQueryStringParameters( queryParametersModifier() .add( param("parameterToAddOne", "addedValue"), param("parameterToAddTwo", "addedValue") ) .replace( param("overrideParameterToReplace", "replacedValue"), param("requestParameterToReplace", "replacedValue"), param("extraParameterToReplace", "shouldBeIgnore") ) .remove( "overrideParameterToRemove", "requestParameterToRemove" ) ) // this modifies the set of headers .withHeaders( headersModifier() .add( header("headerToAddOne", "addedValue"), header("headerToAddTwo", "addedValue") ) .replace( header("overrideHeaderToReplace", "replacedValue"), header("requestHeaderToReplace", "replacedValue"), header("extraHeaderToReplace", "shouldBeIgnore") ) .remove( "overrideHeaderToRemove", "requestHeaderToRemove" ) ) .withCookies( cookiesModifier() .add( cookie("cookieToAddOne", "addedValue"), cookie("cookieToAddTwo", "addedValue") ) .replace( cookie("overrideCookieToReplace", "replacedValue"), cookie("requestCookieToReplace", "replacedValue"), ``` ``` -------------------------------- ### JavaScript: Setup Request Matcher Expectation Source: https://www.mock-server.com/mock_server/getting_started Sets up a request matcher expectation using the MockServer JavaScript client. This example demonstrates how to define the request and response objects to be mocked. The client is initialized with the server host and port. ```javascript var mockServerClient = require('mockserver-client').mockServerClient; mockServerClient("localhost", 1080).mockAnyResponse({ "httpRequest": { "method": "POST", "path": "/login", "body": { "username": "foo", "password": "bar" } }, "httpResponse": { "statusCode": 302, "headers": { "Location": [ "https://www.mock-server.com" ] }, "cookies": { "sessionId": "2By8LOhBmaW5nZXJwcmludCIlMDAzMW" } } }).then( function () { console.log("expectation created"); }, function (error) { console.log(error); } ); ``` -------------------------------- ### MockServer Expectation - XML Body Match with Placeholders Source: https://www.mock-server.com/mock_server/getting_started Demonstrates how to set up an expectation using XML body matching with placeholders for flexible matching. Examples are provided for Java, JavaScript, and curl. ```APIDOC ## POST /mockserver/expectation (with placeholders) ### Description Sets up a mock server expectation to match an XML request body using placeholders for flexible matching (e.g., ignoring specific fields or checking for numbers). Refer to XMLUnit documentation for placeholder details. ### Method PUT ### Endpoint http://localhost:1080/mockserver/expectation ### Request Body - **httpRequest** (object) - Required - Details of the incoming HTTP request to match. - **body** (object) - Required - The request body criteria. - **type** (string) - Required - Type of the body, e.g., "XML". - **xml** (string) - Required - The XML content with placeholders to match. - **httpResponse** (object) - Required - Details of the HTTP response to return. - **body** (string) - Required - The response body content. ### Request Example (curl) ```bash curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{ "httpRequest" : { "body" : { "type" : "XML", "xml" : "\n Everyday Italian ${xmlunit.ignore} ${xmlunit.isNumber} 30.00 " } }, "httpResponse" : { "body" : "some_response_body" } }' ``` ### Request Example (Java) ```java new MockServerClient("localhost", 1080) .when( request() .withBody( xml("\n" + " \n" + " Everyday Italian\n" + " ${xmlunit.ignore}\n" + " ${xmlunit.isNumber}\n" + " 30.00\n" + " \n" + "") ) ) .respond( response() .withBody("some_response_body") ); ``` ### Request Example (JavaScript) ```javascript var mockServerClient = require('mockserver-client').mockServerClient; mockServerClient("localhost", 1080).mockAnyResponse({ "httpRequest" : { "body" : { "type" : "XML", "xml" : "\n" + " \n" + " Everyday Italian\n" + " ${xmlunit.ignore}\n" + " ${xmlunit.isNumber}\n" + " 30.00\n" + " \n" + "" } }, "httpResponse" : { "body" : "some_response_body" } }).then( function () { console.log("expectation created"); }, function (error) { console.log(error); } ); ``` ### Response (Success response indicates the expectation was set up. Error responses will detail the issue.) ``` -------------------------------- ### MockServer Expectation - Header Matching Key Style Source: https://www.mock-server.com/mock_server/getting_started This example shows how to match headers using different key matching styles, specifically 'MATCHING_KEY' where all values with the same key must match. ```APIDOC ## PUT /mockserver/expectation ### Description Sets up a mock server expectation where headers are matched using the 'MATCHING_KEY' style, ensuring all values associated with a header key must match. ### Method PUT ### Endpoint /mockserver/expectation ### Parameters #### Request Body - **httpRequest** (object) - Required - The definition of the incoming request to match. - **path** (string) - Required - The path of the request. - **headers** (object) - Required - Headers to match against. - **keyMatchStyle** (string) - Required - The style for matching header keys. Use 'MATCHING_KEY' to ensure all values with the same key match. - **multiValuedHeader** (array of strings) - Required - Values for a multi-valued header. - **headerTwo** (array of strings) - Required - Values for header 'headerTwo'. - **httpResponse** (object) - Required - The definition of the response to return. - **body** (string) - Required - The body of the response. ### Request Example ```json { "httpRequest": { "path": "/some/path", "headers": { "keyMatchStyle": "MATCHING_KEY", "multiValuedHeader": ["value.*"], "headerTwo": ["headerTwoValue"] } }, "httpResponse": { "body": "some_response_body" } } ``` ### Response #### Success Response (200) Confirms the successful creation of the mock server expectation. ``` -------------------------------- ### MockServer: Expectation with Cookie and Query Parameter (Java) Source: https://www.mock-server.com/mock_server/getting_started Initiates the setup for a mock server expectation in Java, specifying the HTTP method as GET and the path as '/view/cart'. This is the beginning of defining a request match, likely to be followed by cookie and query parameter matching. ```java new MockServerClient("localhost", 1080) .when( request() .withMethod("GET") .withPath("/view/cart") ``` -------------------------------- ### Literal Response with Binary PNG Body Source: https://www.mock-server.com/mock_server/getting_started This example demonstrates how to configure the mock server to return a literal binary PNG response for a specific request path. ```APIDOC ## Mock PNG Endpoint ### Description Configures the mock server to respond with a binary PNG image when a request matches the specified path pattern. ### Method (Implicitly handled by MockServerClient) ### Endpoint /ws/rest/user/[0-9]+/icon/[0-9]+\.png ### Parameters #### Request Body (Not applicable for this example, relies on path matching) ### Request Example (N/A - This is a configuration, not a direct request to the mock server) ### Response #### Success Response (200) - **content-type** (string) - "image/png" - **content-disposition** (string) - "form-data; name=\"test.png\"; filename=\"test.png\"" - **body** (binary) - The binary PNG data. #### Response Example (Binary data, not represented as JSON) ``` -------------------------------- ### PUT /mockserver/expectation (JavaScript Templated Response) Source: https://www.mock-server.com/mock_server/getting_started This example demonstrates how to set up a mock response using a JavaScript template, including the option to add a delay. ```APIDOC ## PUT /mockserver/expectation (JavaScript Templated Response) ### Description Configures a mock server expectation with a response defined by a JavaScript template. This allows for dynamic response generation based on request details. A delay can also be specified. ### Method PUT ### Endpoint /mockserver/expectation ### Parameters #### Request Body - **httpRequest** (object) - Required - Defines the incoming request to match. - **path** (string) - Required - The path of the request. - **httpResponseTemplate** (object) - Required - Defines the response to return when the request matches. - **template** (string) - Required - The JavaScript template string for the response. - **templateType** (string) - Required - Must be "JAVASCRIPT". - **delay** (object) - Optional - Specifies a delay before returning the response. - **timeUnit** (string) - Required - The time unit for the delay (e.g., "MINUTES"). - **value** (number) - Required - The value of the delay. ### Request Example ```json { "httpRequest": { "path": "/some/path" }, "httpResponseTemplate": { "template": "if (request.method === \"POST\" && request.path === \"/some/path\") { return { statusCode: 200, body: JSON.stringify({name: \"value\"}) }; } else { return { statusCode: 406, body: request.body }; }", "templateType": "JAVASCRIPT", "delay": {"timeUnit": "MINUTES", "value": 2} } } ``` ### Response #### Success Response (200) Indicates that the expectation has been successfully created. #### Response Example (No specific response example provided in the input.) ``` -------------------------------- ### GET /view/cart - Match by Cookie and Query Parameter Source: https://www.mock-server.com/mock_server/getting_started This section details how to set up a mock server expectation to match a GET request to /view/cart based on specific cookie and query parameters. It includes examples in Java, JavaScript, and cURL. ```APIDOC ## GET /view/cart ### Description This endpoint mocks a GET request to retrieve cart information. It matches requests based on a specific session cookie and cartId query parameter. ### Method GET ### Endpoint /view/cart ### Parameters #### Query Parameters - **cartId** (string) - Required - The unique identifier for the shopping cart. #### Request Body This endpoint does not have a request body. ### Request Example (cURL) ```bash curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{ "httpRequest" : { "method" : "GET", "path" : "/view/cart", "queryStringParameters" : { "cartId" : [ "055CA455-1DF7-45BB-8535-4F83E7266092" ] }, "cookies" : { "session" : "4930456C-C718-476F-971F-CB8E047AB349" } }, "httpResponse" : { "body" : "some_response_body" } }' ``` ### Response #### Success Response (200) - **body** (string) - The response body indicating success or cart details. #### Response Example ```json { "body": "some_response_body" } ``` ``` -------------------------------- ### MockServer Expectation - Optional Header Matching Source: https://www.mock-server.com/mock_server/getting_started This example illustrates how to configure a mock server expectation that matches a request path and can optionally include specific headers. ```APIDOC ## PUT /mockserver/expectation ### Description Configures a mock server expectation to match a request path, with support for matching one of several specified headers or specific optional headers. ### Method PUT ### Endpoint /mockserver/expectation ### Parameters #### Request Body - **httpRequest** (object) - Required - The definition of the incoming request to match. - **path** (string) - Required - The path of the request. - **headers** (object) - Optional - Headers to match against. - **headerOne|headerTwo** (array of strings) - Optional - Matches requests containing either 'headerOne' or 'headerTwo'. - **?headerOne** (array of strings) - Optional - Matches an optional header named 'headerOne'. - **?headerTwo** (array of strings) - Optional - Matches an optional header named 'headerTwo'. - **httpResponse** (object) - Required - The definition of the response to return. - **body** (string) - Required - The body of the response. ### Request Example ```json { "httpRequest": { "path": "/some/path", "headers": { "headerOne|headerTwo": [".*"], "?headerOne": ["headerOneValue"], "?headerTwo": ["headerTwoValue"] } }, "httpResponse": { "body": "some_response_body" } } ``` ### Response #### Success Response (200) Indicates that the expectation was successfully created. ``` -------------------------------- ### Match Request by Headers Source: https://www.mock-server.com/mock_server/getting_started This section details how to configure the mock server to match requests based on specific HTTP headers. It includes examples for setting exact header values and their corresponding keys. ```APIDOC ## Match Request by Headers ### Description This endpoint allows you to define expectations for incoming requests based on specific HTTP headers. You can specify header names and their exact values to match against. ### Method `PUT` ### Endpoint `/mockserver/expectation ### Parameters #### Request Body - **httpRequest** (object) - Required - The details of the incoming HTTP request to match. - **method** (string) - Optional - The HTTP method of the request (e.g., `GET`). - **path** (string) - Required - The path of the request. - **headers** (object) - Optional - Defines the headers to match. - **Header-Name** (array) - An array of strings representing the expected values for the specified header. - **httpResponse** (object) - Required - The HTTP response to return when the request matches. - **body** (string) - Required - The body of the response. ### Request Example (REST API) ```json { "httpRequest" : { "method" : "GET", "path" : "/some/path", "headers" : { "Accept" : [ "application/json" ], "Accept-Encoding" : [ "gzip, deflate, br" ] } }, "httpResponse" : { "body" : "some_response_body" } } ``` ### Response #### Success Response (200) Typically returns an acknowledgment of the expectation being set. ``` -------------------------------- ### JavaScript Templated Forward Source: https://www.mock-server.com/mock_server/getting_started This example demonstrates using a JavaScript template to dynamically construct the forwarded request based on incoming request parameters. ```APIDOC ## PUT /mockserver/expectation ### Description Configures a mock expectation to forward a request using a JavaScript template to dynamically generate the forwarded request details, including path, query parameters, headers, and body. ### Method PUT ### Endpoint /mockserver/expectation ### Parameters #### Request Body - **httpRequest** (object) - Required - The incoming request to match. - **path** (string) - The path of the incoming request. - **httpForwardTemplate** (object) - Required - Defines the template for the forwarded request. - **template** (string) - Required - The JavaScript template string. It can access the incoming `request` object. - **templateType** (string) - Required - The type of the template (e.g., "JAVASCRIPT"). ### Request Example ```json { "httpRequest": { "path": "/some/path" }, "httpForwardTemplate": { "template": "return {\n 'path' : \"/somePath\",\n 'queryStringParameters' : {\n 'userId' : request.queryStringParameters && request.queryStringParameters['userId']\n },\n 'headers' : {\n 'Host' : [ \"localhost:1081\" ]\n },\n 'body': JSON.stringify({'name': 'value'})\n};", "templateType": "JAVASCRIPT" } } ``` ### Response #### Success Response (200) (Indicates successful registration of the expectation.) #### Response Example (Not provided in the input text.) ``` -------------------------------- ### GET /pets Source: https://www.mock-server.com/mock_server/getting_started Retrieves a list of all pets. Supports pagination with a limit parameter and includes headers for next page links. ```APIDOC ## GET /pets ### Description Retrieves a list of all pets. Supports pagination with a limit parameter and includes headers for next page links. ### Method GET ### Endpoint /pets ### Parameters #### Query Parameters - **limit** (integer) - Optional - How many items to return at one time (max 100) ### Request Example ```json { "example": "No request body for GET request" } ``` ### Response #### Success Response (200) - **x-next** (string) - A link to the next page of responses - **Pets** (object) - A paged array of pets #### Response Example ```json { "example": "{\"id\": 1, \"name\": \"Buddy\", \"tag\": \"dog\"}" } ``` #### Error Response (500) - **x-code** (integer) - The error code - **message** (string) - The error message #### Error Response Example ```json { "example": "{\"code\": 90, \"message\": \"unexpected error\"}" } ``` ``` -------------------------------- ### Mock Server - JSON Body Matching with Placeholders Source: https://www.mock-server.com/mock_server/getting_started This example shows how to use placeholders like `${json-unit.ignore-element}` and `${json-unit.any-boolean}` within the JSON request body to make matching more flexible. ```APIDOC ## PUT /mockserver/expectation (with JSON placeholders) ### Description Sets an expectation for the mock server to match an incoming HTTP request with a JSON body that includes placeholders, allowing certain fields to be ignored or match any boolean value. ### Method PUT ### Endpoint /mockserver/expectation ### Parameters #### Request Body - **httpRequest** (object) - Required - Defines the criteria for matching an incoming request. - **body** (object) - Required - The request body to match. - **type** (string) - Required - "JSON" - **json** (string) - Required - The JSON string with placeholders to match. - Example: `{"id": 1, "name": "A green door", "price": "${json-unit.ignore-element}", "enabled": "${json-unit.any-boolean}", "tags": ["home", "green"]}` - **matchType** (string) - Required - "ONLY_MATCHING_FIELDS" - **httpResponse** (object) - Required - Defines the response to be returned. - **statusCode** (integer) - Required - 202 - **body** (string) - Required - "some_response_body" ### Request Example ```json { "httpRequest" : { "body" : { "type" : "JSON", "json": "{\n \"id\": 1,\n \"name\": \"A green door\",\n \"price\": \"${json-unit.ignore-element}\",\n \"enabled\": \"${json-unit.any-boolean}\",\n \"tags\": [\"home\", \"green\"]\n}", "matchType": "ONLY_MATCHING_FIELDS" } }, "httpResponse": { "statusCode": 202, "body": "some_response_body" } } ``` ### Response #### Success Response (200 OK) Indicates that the expectation was successfully created. #### Response Example (No specific response body is detailed for success in the provided text.) ``` -------------------------------- ### Set Mock Response with Connection Options (JavaScript) Source: https://www.mock-server.com/mock_server/getting_started Sets up a mock server to respond with a given body and connection options, such as closing the socket with a delay. This example uses the mockserver-client library for Node.js. ```JavaScript var mockServerClient = require('mockserver-client').mockServerClient; mockServerClient("localhost", 1080).mockAnyResponse({ "httpRequest" : { "path" : "/some/path" }, "httpResponse" : { "body" : "some_response_body", "connectionOptions" : { "closeSocket" : true, "closeSocketDelay" : { "timeUnit" : "MILLISECONDS", "value" : 500 } } } }).then( function () { console.log("expectation created"); }, function (error) { console.log(error); } ); ``` -------------------------------- ### MockServer Expectation - XML Body Match Source: https://www.mock-server.com/mock_server/getting_started Sets up a mock server expectation to match a request with a specific XML body and respond with a predefined body. Examples are provided for Java, JavaScript, and curl. ```APIDOC ## POST /mockserver/expectation ### Description Sets up a mock server expectation to match a request with a specific XML body and respond with a predefined body. ### Method PUT ### Endpoint http://localhost:1080/mockserver/expectation ### Request Body - **httpRequest** (object) - Required - Details of the incoming HTTP request to match. - **body** (object) - Required - The request body criteria. - **type** (string) - Required - Type of the body, e.g., "XML". - **xml** (string) - Required - The XML content to match. - **httpResponse** (object) - Required - Details of the HTTP response to return. - **body** (string) - Required - The response body content. ### Request Example (curl) ```bash curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{ "httpRequest" : { "body" : { "type" : "XML", "xml" : " Everyday ItalianGiada De Laurentiis200530.00 " } }, "httpResponse" : { "body" : "some_response_body" } }' ``` ### Request Example (Java) ```java new MockServerClient("localhost", 1080) .when( request() .withBody( xml("\n" + " \n" + " Everyday Italian\n" + " Giada De Laurentiis\n" + " 2005\n" + " 30.00\n" + " \n" + "") ) ) .respond( response() .withBody("some_response_body") ); ``` ### Request Example (JavaScript) ```javascript var mockServerClient = require('mockserver-client').mockServerClient; mockServerClient("localhost", 1080).mockAnyResponse({ "httpRequest": { "body": { "type": "XML", "xml": "\n" + " \n" + " Everyday Italian\n" + " Giada De Laurentiis\n" + " 2005\n" + " 30.00\n" + " \n" + "" } }, "httpResponse": { "body": "some_response_body" } }).then( function () { console.log("expectation created"); }, function (error) { console.log(error); } ); ``` ### Response (Success response indicates the expectation was set up. Error responses will detail the issue.) ``` -------------------------------- ### Match Request by OpenAPI Specification Source: https://www.mock-server.com/mock_server/getting_started This section demonstrates how to configure MockServer to match requests based on an OpenAPI v3 specification. Examples are provided for Java and JavaScript clients, showing how to reference the OpenAPI spec via URL. ```APIDOC ## Match Request by OpenAPI Specification ### Description Configures MockServer to match requests based on an OpenAPI v3 specification. This allows for more complex and structured request matching. ### Parameters #### Request Body - **httpRequest** (object) - Required - Defines the request matching criteria. - **specUrlOrPayload** (string) - Mandatory. Specifies the OpenAPI v3 specification. Can be an HTTP/HTTPS URL, File URL, classpath location, inline JSON object, or inline escaped YAML string. - **operationId** (string) - Optional. Specifies which operation to match against. If empty or null, all operations are matched. - **httpResponse** (object) - Required - Defines the response to return when the request matches. - **body** (string) - The response body. ### Request Example (Java) ```java import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import static org.mockserver.openapi.OpenAPIDefinition.openAPI; new MockServerClient("localhost", 1080) .when( openAPI( "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json" ) ) .respond( response() .withBody("some_response_body") ); ``` ### Request Example (JavaScript) ```javascript var mockServerClient = require('mockserver-client').mockServerClient; mockServerClient("localhost", 1080).mockAnyResponse({ "httpRequest": { "specUrlOrPayload": "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json" }, "httpResponse": { "body": "some_response_body" } }); ``` ``` -------------------------------- ### Java: Setup Request Matcher Expectation Source: https://www.mock-server.com/mock_server/getting_started Sets up a request matcher expectation using the MockServer Java client. This involves defining the request details (method, path, body) and the corresponding response (status code, cookies, headers). The Java client requires the 'mockserver-client-java-no-dependencies' dependency. ```java new MockServerClient("localhost", 1080) .when( request() .withMethod("POST") .withPath("/login") .withBody("{username: 'foo', password: 'bar'}") ) .respond( response() .withStatusCode(302) .withCookie( "sessionId", "2By8LOhBmaW5nZXJwcmludCIlMDAzMW" ) .withHeader( "Location", "https://www.mock-server.com" ) ); ``` ```xml org.mock-server mockserver-client-java-no-dependencies RELEASE ``` -------------------------------- ### Mock Any Response (Method Not GET) Source: https://www.mock-server.com/mock_server/getting_started Sets up a mock response for any request that does not have the GET method. This is useful for testing non-GET endpoints. ```APIDOC ## POST /mockserver/expectation ### Description Sets up a mock response for any request that does not have the GET method. This is useful for testing non-GET endpoints. ### Method PUT ### Endpoint /mockserver/expectation ### Parameters #### Request Body - **httpRequest** (object) - Required - Defines the request to match. - **method** (string) - Required - The HTTP method of the request. Use `!GET` to match any method except GET. - **httpResponse** (object) - Required - Defines the response to return. - **body** (string) - Required - The body of the mock response. ### Request Example ```json { "httpRequest": { "method": "!GET" }, "httpResponse": { "body": "some_response_body" } } ``` ### Response #### Success Response (200) (No specific success response body defined in the example) #### Response Example (No specific response example provided, but the creation of the expectation is confirmed.) ``` -------------------------------- ### Match Request by OpenAPI Spec URL - JavaScript Source: https://www.mock-server.com/mock_server/getting_started JavaScript example to configure MockServer to match requests against an OpenAPI v3 specification provided via a URL. This approach simplifies the creation of complex request matchers. ```JavaScript var mockServerClient = require('mockserver-client').mockServerClient; mockServerClient("localhost", 1080).mockAnyResponse({ "httpRequest": { "specUrlOrPayload": "https://raw.githubusercontent.com/mock-server/mockserver/master/mockserver-integration-testing/src/main/resources/org/mockserver/openapi/openapi_petstore_example.json" }, "httpResponse": { ``` -------------------------------- ### Request Properties Matcher Examples - Mock Server Source: https://www.mock-server.com/mock_server/getting_started Illustrates how to use the request properties matcher to match various components of an HTTP request. This includes matching by method, path, query parameters, headers, and body using different matching strategies like string, regex, and JSON schema. ```Java import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; // Matcher for method and path mockServer.when( request() .withMethod("GET") .withPath("/some/path") ) .respond( response() .withStatusCode(200) .withBody("GET response") ); // Matcher for query parameters mockServer.when( request() .withPath("/querypath") .withQueryStringParameter("name", "value") ) .respond( response() .withStatusCode(200) .withBody("Query parameter response") ); // Matcher for headers mockServer.when( request() .withPath("/headerpath") .withHeader("Content-Type", "application/json") ) .respond( response() .withStatusCode(200) .withBody("Header response") ); // Matcher for body (plain text) mockServer.when( request() .withPath("/bodypath") .withBody("exact body content") ) .respond( response() .withStatusCode(200) .withBody("Plain text body response") ); // Matcher for body (JSON) mockServer.when( request() .withPath("/jsonbodypath") .withBody("{\"key\": \"value\"}") ) .respond( response() .withStatusCode(200) .withBody("JSON body response") ); // Matcher for body (JSON schema) import static org.mockserver.model.JsonSchemaBody.jsonSchema; mockServer.when( request() .withPath("/jsonschemapath") .withBody(jsonSchema("{\"type\": \"object\", \"properties\": { \"key\": { \"type\": \"string\" } }}")) ) .respond( response() .withStatusCode(200) .withBody("JSON schema response") ); // Matcher for path parameters import static org.mockserver.model.Parameter.param; mockServer.when( request() .withPath("/path/param/value") .withPathParameter("paramName", "paramValue") ) .respond( response() .withStatusCode(200) .withBody("Path parameter response") ); // Matcher using regex for path import static org.mockserver.model.RegexBody.regex; mockServer.when( request() .withMethod("POST") .withPath("/regex/.*") ) .respond( response() .withStatusCode(200) .withBody("Regex path response") ); ``` -------------------------------- ### Match Request by Body Substring (Java, JavaScript, REST API) Source: https://www.mock-server.com/mock_server/getting_started Configure MockServer to match requests where the body contains a specific substring. This is useful for flexible matching of request payloads. Examples demonstrate client-side setup in Java and JavaScript, as well as a direct REST API call to define the expectation. ```Java new MockServerClient("localhost", 1080) .when( request() .withBody(subString("some_string")) ) .respond( response() .withBody("some_response_body") ); ``` ```JavaScript var mockServerClient = require('mockserver-client').mockServerClient; mockServerClient("localhost", 1080).mockAnyResponse({ "httpRequest": { "body": { "type": "STRING", "string": "some_string", "subString": true } }, "httpResponse": { "body": "some_response_body" } }).then( function () { console.log("expectation created"); }, function (error) { console.log(error); } ); ``` ```REST API curl -v -X PUT "http://localhost:1080/mockserver/expectation" -d '{ "httpRequest" : { "body" : { "type": "STRING", "string": "some_string", "subString": true } }, "httpResponse" : { "body" : "some_response_body" } }' ``` -------------------------------- ### Responding Differently for the Same Request Source: https://www.mock-server.com/mock_server/getting_started This section illustrates how to set up multiple responses for the same incoming request, controlling the number of times each response is served. ```APIDOC ## POST /mockserver/expectation (Multiple Responses) ### Description Allows configuring sequential responses for the same request. The mock server will cycle through the defined expectations based on the specified times. ### Method POST ### Endpoint /mockserver/expectation ### Parameters #### Request Body - **httpRequest** (object) - Required - Defines the incoming request to match. - **path** (string) - Required - The path of the request. - **httpResponse** (object) - Required - Defines the response to be returned. - **statusCode** (integer) - Required - The HTTP status code for the response. - **times** (object) - Optional - Specifies how many times this expectation should be active. - **remainingTimes** (integer) - Required - The number of times this expectation can be matched. - **unlimited** (boolean) - Required - If true, the expectation can be matched an unlimited number of times. ### Request Example (Java) ```java MockServerClient mockServerClient = new MockServerClient("localhost", 1080); // respond once with 200, then respond twice with 204, then // respond with 404 as no remaining active expectations mockServerClient .when( request() .withPath("/some/path"), Times.exactly(1) ) .respond( response() .withStatusCode(200) ); mockServerClient .when( request() .withPath("/some/path"), Times.exactly(2) ) .respond( response() .withStatusCode(204) ); ``` ### Request Example (JavaScript) ```javascript var client = require('mockserver-client').mockServerClient("localhost", 1080); // respond once with 200, then respond twice with 204, then // respond with 404 as no remaining active expectations client.mockAnyResponse({ "httpRequest": { "path": "/some/path" }, "httpResponse": { "statusCode": 200 }, "times": { "remainingTimes": 1, "unlimited": false } }).then( function () { console.log("first expectation created"); client.mockAnyResponse({ "httpRequest": { "path": "/some/path" }, "httpResponse": { "statusCode": 204 }, "times": { "remainingTimes": 2, "unlimited": false } }).then( function () { console.log("second expectation created"); }, function (error) { console.log(error); } ); }, function (error) { console.log(error); } ); ``` ### Response #### Success Response (200) Indicates that the expectation was successfully created. #### Response Example (Typically an empty response or a success confirmation) ``` -------------------------------- ### Match Request by Not Matching Method in Java and JavaScript Source: https://www.mock-server.com/mock_server/getting_started This snippet shows how to configure MockServer to match requests that do NOT use a specific HTTP method, such as 'GET'. It includes examples for both Java and JavaScript clients. ```Java new MockServerClient("localhost", 1080) .when( request() // matches any requests that does NOT have a "GET" method .withMethod(not("GET")) ) .respond( response() .withBody("some_response_body") ); ``` ```JavaScript var mockServerClient = require('mockserver-client').mockServerClient; ```