### Full Example Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/index.md A complete example demonstrating how to mock a POST request with a JSON body, content type, status code, and custom header. ```APIDOC ## Example ```apex new HttpMock() .whenPostOn('/api/v1/users') .body('{"id": "123", "name": "John"}') .contentTypeJson() .statusCodeCreated() .header('X-Request-ID', 'abc-123') .mock(); ``` ``` -------------------------------- ### Basic HttpMock Setup Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/README.md Use the HttpMock fluent API to define a simple mock for a GET request. This is a more concise way to mock callouts compared to implementing HttpCalloutMock directly. ```java new HttpMock() .whenGetOn('/api/v1/authorize').body('{"example":"test"}').statusCodeOk() .mock(); ``` -------------------------------- ### POST Request Mock Example Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/index.md A concrete example demonstrating how to mock a POST request to '/api/v1/users' with a JSON response body, CREATED status code, and a custom header. ```apex new HttpMock() .whenPostOn('/api/v1/users') .body('{"id": "123", "name": "John"}') .contentTypeJson() .statusCodeCreated() .header('X-Request-ID', 'abc-123') .mock(); ``` -------------------------------- ### Create a Simple GET Request Mock in Apex Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/getting-started.md Use this snippet to set up a basic mock for a GET request. It defines the endpoint, response body, status code, and activates the mock for testing. ```apex new HttpMock() .whenGetOn('/api/v1/users') .body('{ "name": "John Doe", "email": "john@example.com" }') .statusCodeOk() .mock(); ``` -------------------------------- ### Basic Pattern Example Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/index.md Illustrates the fundamental structure for creating a mock using the HTTP Mock Lib. ```APIDOC ## Basic Pattern Every mock follows this pattern: ```apex new HttpMock() .when[Method]On('/endpoint') // 1. Define endpoint .body('response') // 2. Set response .statusCode[Code]() // 3. Set status .header('key', 'value') // 4. Optional headers .mock(); // 5. Activate ``` ``` -------------------------------- ### Development Setup and Deployment Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/CONTRIBUTING.md Set up a scratch org for testing and deploy the project. Includes commands for creating the org and deploying the project. ```bash # Create scratch org for testing sf org create scratch -f config/project-scratch-def.json -a dev sf project deploy start -o dev # Run tests sf apex run test -o dev -l RunLocalTests ``` -------------------------------- ### Chaining Example Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/index.md Demonstrates the chaining capability of HTTP Mock Lib methods, allowing multiple configurations to be applied sequentially. ```APIDOC ## Chaining All methods (except `mock()`) return `HttpMock`, allowing you to chain multiple calls: ```apex new HttpMock() .whenGetOn('/api/v1/data') .body('{"data": []}') .contentTypeJson() .statusCodeOk() .header('Cache-Control', 'no-cache') .header('X-API-Version', 'v1') .mock(); ``` ``` -------------------------------- ### Activate Mock Configuration with mock() Source: https://context7.com/beyond-the-cloud-dev/http-mock-lib/llms.txt Finalizes mock setup and registers it with Salesforce's Test.setMock(). Must be called before Test.startTest(). ```apex new HttpMock() .whenGetOn('/api/v1/authorize') .body('{"token": "aZ3Xb7Qk", "expires_in": 3600}') .contentTypeJson() .statusCodeOk() .whenPostOn('/api/v1/items') .body('{"id": "item-999", "success": true}') .contentTypeJson() .statusCodeCreated() .whenDeleteOn('/api/v1/items/item-999') .statusCodeNoContent() .mock(); // <-- registers all three mocks at once ``` -------------------------------- ### Mock Execution Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/README.md Method to finalize the mock setup and apply it. ```APIDOC ## Mock Execution ### Description This method applies the configured mock to the HTTP callouts. ### Method - `mock()`: Executes the mock setup. ``` -------------------------------- ### mock() — Activate the mock configuration Source: https://context7.com/beyond-the-cloud-dev/http-mock-lib/llms.txt Finalizes the mock setup and registers it with Salesforce's `Test.setMock()`. Must be called before `Test.startTest()`. All preceding `when*On()` chains are active after this call. ```APIDOC ## mock() — Activate the mock configuration ### Description Finalizes the mock setup and registers it with Salesforce's `Test.setMock()`. Must be called before `Test.startTest()`. All preceding `when*On()` chains are active after this call. ### Example ```apex @IsTest static void testFullAuthAndCreateFlow() { new HttpMock() .whenGetOn('/api/v1/authorize') .body('{"token": "aZ3Xb7Qk", "expires_in": 3600}') .contentTypeJson() .statusCodeOk() .whenPostOn('/api/v1/items') .body('{"id": "item-999", "success": true}') .contentTypeJson() .statusCodeCreated() .whenDeleteOn('/api/v1/items/item-999') .statusCodeNoContent() .mock(); // <-- registers all three mocks at once Test.startTest(); HttpResponse authResp = new TestApi().makeCallout('GET', '/api/v1/authorize'); HttpResponse createResp = new TestApi().makeCallout('POST', '/api/v1/items'); HttpResponse deleteResp = new TestApi().makeCallout('DELETE', '/api/v1/items/item-999'); Test.stopTest(); Assert.areEqual(200, authResp.getStatusCode()); Assert.areEqual(201, createResp.getStatusCode()); Assert.areEqual(204, deleteResp.getStatusCode()); } ``` ``` -------------------------------- ### Multiple Endpoints Example Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/index.md Shows how to mock multiple distinct endpoints within a single test context by chaining endpoint definitions. ```APIDOC ## Multiple Endpoints You can mock multiple endpoints in a single test by chaining endpoint definitions: ```apex new HttpMock() .whenGetOn('/api/auth') .body('{"token": "xyz"}') .statusCodeOk() .whenPostOn('/api/data') .body('{"success": true}') .statusCodeCreated() .whenDeleteOn('/api/data/1') .statusCodeNoContent() .mock(); ``` ``` -------------------------------- ### Mock GET Request with 200 OK Status Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Use `statusCodeOk()` to set the HTTP status code to 200 for a successful GET request mock. This is suitable for general success responses. ```apex new HttpMock() .whenGetOn('/api/users') .body('{"users": []}') .statusCodeOk() .mock(); ``` -------------------------------- ### Define HTTP Endpoints for Mocking in Apex Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/getting-started.md This snippet demonstrates how to specify different HTTP methods (GET, POST, PUT, DELETE) and endpoints for your mocks. ```apex new HttpMock() .whenGetOn('/api/v1/users') // GET request .whenPostOn('/api/v1/users') // POST request .whenPutOn('/api/v1/users/1') // PUT request .whenDeleteOn('/api/v1/users/1') // DELETE request ``` -------------------------------- ### Mock a GET Endpoint Source: https://context7.com/beyond-the-cloud-dev/http-mock-lib/llms.txt Registers a mock response for an HTTP GET request. Defaults to status 200, content-type application/json, and an empty JSON body. ```apex new HttpMock() .whenGetOn('/api/v1/users/123') .body('{"id": "123", "name": "John Doe", "email": "john@example.com"}') .contentTypeJson() .statusCodeOk() .mock(); Test.startTest(); HttpResponse response = new TestApi().makeCallout('GET', '/api/v1/users/123'); Test.stopTest(); Assert.areEqual(200, response.getStatusCode()); Map body = (Map) JSON.deserializeUntyped(response.getBody()); Assert.areEqual('John Doe', body.get('name')); ``` -------------------------------- ### GET Request Mocking Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/http-methods.md Retrieve data by mocking a GET request to a specific endpoint. You can define the response body and status code. ```APIDOC ## GET /api/v1/users/123 ### Description Retrieve data for a specific user. ### Method GET ### Endpoint /api/v1/users/123 ### Request Example ```json {} ``` ### Response #### Success Response (200) - **id** (string) - The user's ID. - **name** (string) - The user's name. ### Response Example ```json { "id": "123", "name": "John" } ``` ``` -------------------------------- ### Mock HTTP Call with Static Resource Body Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/response-body.md Mock a GET request to '/api/users' and load the response body from a Static Resource named 'UsersResponseMock'. ```apex new HttpMock() .whenGetOn('/api/users') .staticResource('UsersResponseMock') .statusCodeOk() .mock(); ``` -------------------------------- ### Mock HTTP Call with String Body Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/response-body.md Use this to mock a GET request to '/api/users' and return a JSON string as the response body. ```apex new HttpMock() .whenGetOn('/api/users') .body('{"id": "123", "name": "John Doe"}') .mock(); ``` -------------------------------- ### Mock GET Request Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/http-methods.md Mock a GET request to retrieve data from a specific endpoint. Set the response body and status code for the mock. ```apex new HttpMock() .whenGetOn('/api/v1/users/123') .body('{"id": "123", "name": "John"}') .statusCodeOk() .mock(); ``` -------------------------------- ### Advanced HttpMock Setup with Multiple Mocks Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/README.md Configure multiple mock responses for different endpoints and HTTP methods within a single test method. This allows for testing complex scenarios with various callouts. ```java @IsTest private class MyTest { @IsTest static void calloutTest() { new HttpMock() .whenGetOn('/api/v1/authorize').body('{ "token": "aZ3Xb7Qk" }').statusCodeOk() .whenPostOn('/api/v1/create').body('{ "success": true, "message": null }').statusCodeOk() .mock(); Test.startTest(); new CalloutService().makeCallout(); Test.stopTest(); // Asserts Assert.areEqual(..., ...); } } ``` -------------------------------- ### Mock a GET endpoint Source: https://context7.com/beyond-the-cloud-dev/http-mock-lib/llms.txt Registers a mock response for an HTTP GET request to the given endpoint path. The endpoint is matched by substring against the full URL. Defaults: status 200, content-type `application/json`, body `{}`. ```APIDOC ## whenGetOn(String endpoint) ### Description Registers a mock response for an HTTP GET request to the given endpoint path. The endpoint is matched by substring against the full URL, so `/api/v1/users` matches `https://api.example.com/api/v1/users`. Defaults: status 200, content-type `application/json`, body `{}`. ### Method GET ### Endpoint [endpoint] ### Parameters #### Path Parameters - **endpoint** (String) - Required - The endpoint path to mock. ### Request Example ```apex new HttpMock() .whenGetOn('/api/v1/users/123') .body('{"id": "123", "name": "John Doe", "email": "john@example.com"}') .contentTypeJson() .statusCodeOk() .mock(); ``` ### Response #### Success Response (200) - **body** (String) - The response body. - **contentType** (String) - The content type of the response. - **statusCode** (Integer) - The HTTP status code of the response. #### Response Example ```json { "id": "123", "name": "John Doe", "email": "john@example.com" } ``` ``` -------------------------------- ### Mock HTTP Call with XML Body Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/response-body.md Mock a GET request to '/api/users/123' and return an XML string as the response body. Ensure the content type is set to XML. ```apex String xmlResponse = '' + '' + '123' + 'John Doe' + ''; new HttpMock() .whenGetOn('/api/users/123') .body(xmlResponse) .contentTypeXml() .statusCodeOk() .mock(); ``` -------------------------------- ### Mock GET Request with 404 Not Found Status Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Use `statusCodeNotFound()` to mock a response when the requested resource cannot be found on the server. This is a common error for incorrect URLs or non-existent IDs. ```apex new HttpMock() .whenGetOn('/api/users/999') .body('{"error": "User not found"}') .statusCodeNotFound() .mock(); ``` -------------------------------- ### Mock GET Request with 403 Forbidden Status Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Use `statusCodeForbidden()` to mock a response indicating that the client does not have permission to access the resource, even with valid authentication. ```apex new HttpMock() .whenGetOn('/api/admin') .body('{"error": "Access denied"}') .statusCodeForbidden() .mock(); ``` -------------------------------- ### Mock HTTP Call with JSON String Body Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/response-body.md Mock a GET request to '/api/v1/token' and return a JSON string representing an access token. ```apex new HttpMock() .whenGetOn('/api/v1/token') .body('{"access_token": "abc123", "expires_in": 3600}') .statusCodeOk() .mock(); ``` -------------------------------- ### Mock HTTP Call with Blob Body Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/response-body.md Mock a GET request to '/api/documents/123' and return binary data (Blob) for a PDF file. Ensure the content type is set to PDF. ```apex Blob pdfData = Blob.valueOf('PDF content here'); new HttpMock() .whenGetOn('/api/documents/123') .body(pdfData) .contentTypePdf() .statusCodeOk() .mock(); ``` -------------------------------- ### Set HTTP Status Code Source: https://context7.com/beyond-the-cloud-dev/http-mock-lib/llms.txt Employ semantic convenience methods like `statusCodeOk()` or `statusCodeUnauthorized()` to set common HTTP status codes. For custom codes, use `statusCode(Integer)`. This example simulates a 401 followed by a 200 on retry. ```apex new HttpMock() .whenGetOn('/api/v1/resource') .body('{"error": "Token expired"}') .statusCodeUnauthorized() .whenGetOn('/api/v1/resource') .body('{"data": "secret"}') .statusCodeOk() .mock(); Test.startTest(); HttpResponse first = new TestApi().makeCallout('GET', '/api/v1/resource'); HttpResponse second = new TestApi().makeCallout('GET', '/api/v1/resource'); Test.stopTest(); Assert.areEqual(401, first.getStatusCode()); Assert.areEqual(200, second.getStatusCode()); // Rate-limited endpoint with custom 429 new HttpMock() .whenGetOn('/api/v1/search') .body('{"error": "Too Many Requests"}') .statusCode(429) .header('Retry-After', '60') .mock(); ``` -------------------------------- ### Mock CRUD Operations in a Single Test Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/http-methods.md Demonstrates mocking a sequence of CRUD operations (POST, GET, PUT, DELETE) within a single test method. This is useful for testing full resource lifecycle management. ```apex @IsTest static void testCrudOperations() { new HttpMock() .whenPostOn('/api/v1/users') .body('{"id": "123"}') .statusCodeCreated() .whenGetOn('/api/v1/users/123') .body('{"id": "123", "name": "John"}') .statusCodeOk() .whenPutOn('/api/v1/users/123') .body('{"updated": true}') .statusCodeOk() .whenDeleteOn('/api/v1/users/123') .statusCodeNoContent() .mock(); Test.startTest(); // Your callout here Test.stopTest(); } ``` -------------------------------- ### Chained Method Calls for Mocking Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/index.md Shows how to chain multiple configuration methods (except `mock()`) to build a complex HTTP mock, as each method returns the `HttpMock` instance. ```apex new HttpMock() .whenGetOn('/api/v1/data') .body('{"data": []}') .contentTypeJson() .statusCodeOk() .header('Cache-Control', 'no-cache') .header('X-API-Version', 'v1') .mock(); ``` -------------------------------- ### Clone HTTP Mock Lib Repository Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/CONTRIBUTING.md Clone your forked repository to your local machine and navigate into the project directory. ```bash git clone https://github.com/YOUR_USERNAME/http-mock-lib.git cd http-mock-lib ``` -------------------------------- ### Endpoint Path Matching Guidance Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/http-methods.md Illustrates the correct way to specify endpoint paths when mocking. The mock path should only include the resource path, not the full URL including the domain. ```apex // If your code does: Http http = new Http(); HttpRequest req = new HttpRequest(); req.setEndpoint('https://api.example.com/v1/users'); // Then mock like this: new HttpMock() .whenGetOn('/v1/users') // ✅ Correct - matches path .mock(); // Not like this: new HttpMock() .whenGetOn('https://api.example.com/v1/users') // ❌ Wrong - includes domain .mock(); ``` -------------------------------- ### Basic Mocking Pattern Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/index.md Illustrates the fundamental structure for creating an HTTP mock, including defining the endpoint, response body, status code, and optional headers before activation. ```apex new HttpMock() .when[Method]On('/endpoint') // 1. Define endpoint .body('response') // 2. Set response .statusCode[Code]() // 3. Set status .header('key', 'value') // 4. Optional headers .mock(); // 5. Activate ``` -------------------------------- ### Activation Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/index.md Activates the configured mock. ```APIDOC ## Activation ### `mock()` Activates the mock. This method should be called last in the chain to enable the mock. ``` -------------------------------- ### Activate HTTP Mock Configuration in Apex Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/getting-started.md Call the `.mock()` method to activate the configured HTTP mock. ```apex .mock(); ``` -------------------------------- ### Traditional Mock vs. HTTP Mock Lib Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/index.md Compares the verbose traditional Apex mock class approach with the concise, fluent API of HTTP Mock Lib for mocking HTTP callouts. ```apex global class MockHttpResponseGenerator implements HttpCalloutMock { global HTTPResponse respond(HTTPRequest req) { HttpResponse res = new HttpResponse(); res.setHeader('Content-Type', 'application/json'); res.setBody('{"example":"test"}'); res.setStatusCode(200); return res; } } Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator()); ``` ```apex new HttpMock() .whenGetOn('/api/v1/authorize') .body('{"example":"test"}') .statusCodeOk() .mock(); ``` -------------------------------- ### Run All Apex Tests Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/CONTRIBUTING.md Execute all local Apex tests to ensure code quality before committing changes. ```bash sf apex run test -o dev -l RunLocalTests ``` -------------------------------- ### Mock HTTP Call with Apex Object Body Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/response-body.md Mock a GET request to '/api/users/123' and return an Apex Map object, which will be automatically serialized to JSON. ```apex Map response = new Map{ 'id' => '123', 'name' => 'John Doe', 'email' => 'john@example.com' }; new HttpMock() .whenGetOn('/api/users/123') .body(response) .statusCodeOk() .mock(); ``` -------------------------------- ### Mocking Multiple Endpoints Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/index.md Demonstrates how to mock several distinct endpoints within a single test by chaining multiple endpoint definitions and their configurations before calling `mock()`. ```apex new HttpMock() .whenGetOn('/api/auth') .body('{"token": "xyz"}') .statusCodeOk() .whenPostOn('/api/data') .body('{"success": true}') .statusCodeCreated() .whenDeleteOn('/api/data/1') .statusCodeNoContent() .mock(); ``` -------------------------------- ### Mock GET Request with 401 Unauthorized Status Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Use `statusCodeUnauthorized()` to mock a response requiring authentication. This is used when the client lacks valid authentication credentials. ```apex new HttpMock() .whenGetOn('/api/users') .body('{"error": "Authentication required"}') .statusCodeUnauthorized() .mock(); ``` -------------------------------- ### Mock HTML Response Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/content-types.md Use `contentTypeHtml()` to set the Content-Type header to `text/html` for serving HTML content. ```apex new HttpMock() .whenGetOn('/api/page') .body('

Hello

') .contentTypeHtml() .mock(); ``` -------------------------------- ### Simulate Rate Limiting Headers Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/headers.md Add `X-RateLimit-*` headers to simulate API rate limiting. This helps in testing how clients handle API usage limits. ```apex new HttpMock() .whenGetOn('/api/users') .body('{"users": []}') .header('X-RateLimit-Limit', '100') .header('X-RateLimit-Remaining', '95') .header('X-RateLimit-Reset', '1640000000') .mock(); ``` -------------------------------- ### Mock POST Request Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/http-methods.md Mock a POST request to create a new resource. Specify the request path, response body, and the 'Created' status code. ```apex new HttpMock() .whenPostOn('/api/v1/users') .body('{"id": "456", "created": true}') .statusCodeCreated() .mock(); ``` -------------------------------- ### Mock GET Request with 500 Internal Server Error Status Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Use `statusCodeInternalServerError()` to mock a generic server error. This is used when an unexpected condition occurred on the server. ```apex new HttpMock() .whenGetOn('/api/users') .body('{"error": "Internal server error"}') .statusCodeInternalServerError() .mock(); ``` -------------------------------- ### POST Request Mocking Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/http-methods.md Create new resources by mocking a POST request. Specify the request body and the created status code. ```APIDOC ## POST /api/v1/users ### Description Create a new user resource. ### Method POST ### Endpoint /api/v1/users ### Request Body - **id** (string) - Required - The ID for the new user. ### Request Example ```json { "id": "456" } ``` ### Response #### Success Response (201 Created) - **id** (string) - The ID of the created user. - **created** (boolean) - Indicates if the resource was created. ### Response Example ```json { "id": "456", "created": true } ``` ``` -------------------------------- ### Mock HTTP Call with Default Empty Response Body Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/response-body.md Mock a GET request to '/api/ping' without specifying a body. The response body will default to an empty JSON object '{}'. ```apex new HttpMock() .whenGetOn('/api/ping') .statusCodeOk() .mock(); // Response body: "{}" ``` -------------------------------- ### Mock GET Request with 504 Gateway Timeout Status Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Use `statusCodeGatewayTimeout()` to mock a response indicating that the server, acting as a gateway, did not receive a timely response from an upstream server. ```apex new HttpMock() .whenGetOn('/api/slow-endpoint') .body('{"error": "Gateway timeout"}') .statusCodeGatewayTimeout() .mock(); ``` -------------------------------- ### 201 Created Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Resource successfully created. Use `statusCodeCreated()` to set the status code to 201. ```APIDOC ## 201 Created ### Description Resource successfully created. ### Method POST ### Endpoint /api/users ### Request Example ```apex new HttpMock() .whenPostOn('/api/users') .body('{"id": "123"}') .statusCodeCreated() .mock(); ``` ### Response #### Success Response (201) - **body** (string) - JSON string representing the response body. ``` -------------------------------- ### HTTP Methods Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/index.md Define which HTTP method and endpoint to mock. These methods initiate the mocking process for a specific HTTP verb and URL. ```APIDOC ## HTTP Methods ### `whenGetOn(String endpointToMock)` Mocks a GET request on the specified endpoint. ### `whenPostOn(String endpointToMock)` Mocks a POST request on the specified endpoint. ### `whenPutOn(String endpointToMock)` Mocks a PUT request on the specified endpoint. ### `whenPatchOn(String endpointToMock)` Mocks a PATCH request on the specified endpoint. ### `whenDeleteOn(String endpointToMock)` Mocks a DELETE request on the specified endpoint. ### `whenTraceOn(String endpointToMock)` Mocks a TRACE request on the specified endpoint. ### `whenHeadOn(String endpointToMock)` Mocks a HEAD request on the specified endpoint. ``` -------------------------------- ### Mock GET Request with 503 Service Unavailable Status Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Use `statusCodeServiceUnavailable()` to mock a response indicating that the server is temporarily unable to handle the request due to overload or maintenance. ```apex new HttpMock() .whenGetOn('/api/users') .body('{"error": "Service unavailable"}') .statusCodeServiceUnavailable() .mock(); ``` -------------------------------- ### Configure HTTP Mock Response in Apex Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/getting-started.md Configure the response details for your mock, including the body, content type, status code, and custom headers. ```apex .body('{ "success": true }') // Response body .contentTypeJson() // Content-Type header .statusCodeOk() // HTTP 200 .header('X-Custom', 'value') // Custom header ``` -------------------------------- ### Body Configuration Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/README.md Methods for configuring the request body for the mock response. ```APIDOC ## Body Configuration ### Description Configure the request body for the mock HTTP callout. ### Methods - `body(Object body)`: Sets the request body as an Object. - `body(String body)`: Sets the request body as a String. - `body(Blob body)`: Sets the request body as a Blob. ``` -------------------------------- ### Mock GET Request with 502 Bad Gateway Status Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Use `statusCodeBadGateway()` to mock a response indicating that the server, while acting as a gateway or proxy, received an invalid response from an upstream server. ```apex new HttpMock() .whenGetOn('/api/external') .body('{"error": "Bad gateway"}') .statusCodeBadGateway() .mock(); ``` -------------------------------- ### Mock PDF Response Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/content-types.md Use `contentTypePdf()` to set the Content-Type header to `application/pdf`. The body should be binary data, such as a Blob. ```apex Blob pdfData = generatePdfContent(); new HttpMock() .whenGetOn('/api/report.pdf') .body(pdfData) .contentTypePdf() .mock(); ``` -------------------------------- ### Mocking Multiple HTTP Methods Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/http-methods.md Demonstrates how to mock multiple HTTP methods for different endpoints within a single HttpMock instance for comprehensive testing. ```APIDOC ## Multiple HTTP Methods ### Description Mock multiple HTTP methods for different endpoints in a single test. ### Example Usage ```apex @IsTest static void testCrudOperations() { new HttpMock() .whenPostOn('/api/v1/users') .body('{"id": "123"}') .statusCodeCreated() .whenGetOn('/api/v1/users/123') .body('{"id": "123", "name": "John"}') .statusCodeOk() .whenPutOn('/api/v1/users/123') .body('{"updated": true}') .statusCodeOk() .whenDeleteOn('/api/v1/users/123') .statusCodeNoContent() .mock(); Test.startTest(); // Your callout here Test.stopTest(); } ``` ``` -------------------------------- ### Mock XML Response Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/content-types.md Use `contentTypeXml()` to set the Content-Type header to `application/xml` for returning XML data. ```apex new HttpMock() .whenGetOn('/api/users') .body('John') .contentTypeXml() .mock(); ``` -------------------------------- ### Mock GET Request with Custom Status Code Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Use `statusCode(Integer)` to set a custom HTTP status code for a mocked response when a predefined method is not available. This is useful for non-standard codes like 429 Too Many Requests. ```apex new HttpMock() .whenGetOn('/api/users') .body('{"error": "Too many requests"}') .statusCode(429) .mock(); ``` -------------------------------- ### Mock a POST Endpoint Source: https://context7.com/beyond-the-cloud-dev/http-mock-lib/llms.txt Registers a mock response for an HTTP POST request, often used for resource creation scenarios returning 201 Created. ```apex new HttpMock() .whenPostOn('/api/v1/users') .body('{"id": "456", "created": true}') .contentTypeJson() .statusCodeCreated() .header('Location', '/api/v1/users/456') .mock(); Test.startTest(); HttpResponse response = new TestApi().makeCallout('POST', '/api/v1/users'); Test.stopTest(); Assert.areEqual(201, response.getStatusCode()); Assert.areEqual('/api/v1/users/456', response.getHeader('Location')); ``` -------------------------------- ### Set Authentication and Session Headers Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/headers.md Use `Set-Cookie` for session management and `X-Auth-Token` for API authentication in mocked responses. Ensure `HttpOnly` and `Secure` flags are correctly set for `Set-Cookie`. ```apex new HttpMock() .whenPostOn('/api/login') .body('{"token": "xyz789"}') .header('Set-Cookie', 'session=abc123; HttpOnly; Secure') .header('X-Auth-Token', 'xyz789') .mock(); ``` -------------------------------- ### Header Configuration Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/README.md Method for adding custom headers to the mock response. ```APIDOC ## Header Configuration ### Description Add custom headers to the mock HTTP response. ### Method - `header(String key, String value)`: Adds a header with the specified key and value. ``` -------------------------------- ### Create a New Feature Branch Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/CONTRIBUTING.md Create a new branch for your feature or bug fix using a descriptive name. ```bash git checkout -b feature/my-awesome-feature ``` -------------------------------- ### Mock Using Static Resource Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/release.md Use the `staticResource()` method to load response bodies from Salesforce Static Resources. This is useful for large or complex payloads. Ensure the Static Resource exists to avoid `StaticResourceNotFoundException`. ```apex new HttpMock() .whenGetOn('/api/v1/users') .staticResource('UsersResponseMock') .statusCodeOk() .mock(); ``` -------------------------------- ### Content Type Configuration Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/README.md Methods for setting the Content-Type header for the mock response. ```APIDOC ## Content Type Configuration ### Description Set the `Content-Type` header for the mock HTTP response. ### Methods - `contentTypePlainText()`: Sets Content-Type to `text/plain`. - `contentTypeHtml()`: Sets Content-Type to `text/html`. - `contentTypeCsv()`: Sets Content-Type to `text/csv`. - `contentTypeJson()`: Sets Content-Type to `application/json`. - `contentTypeXml()`: Sets Content-Type to `application/xml`. - `contentTypePdf()`: Sets Content-Type to `application/pdf`. - `contentTypeFormUrlencoded()`: Sets Content-Type to `application/x-www-form-urlencoded`. - `contentType(String contentType)`: Sets a custom Content-Type. ``` -------------------------------- ### Mock a POST endpoint Source: https://context7.com/beyond-the-cloud-dev/http-mock-lib/llms.txt Registers a mock response for an HTTP POST request. Commonly used to simulate resource creation flows returning 201 Created. ```APIDOC ## whenPostOn(String endpoint) ### Description Registers a mock response for an HTTP POST request. Commonly used to simulate resource creation flows returning 201 Created. ### Method POST ### Endpoint [endpoint] ### Parameters #### Path Parameters - **endpoint** (String) - Required - The endpoint path to mock. ### Request Example ```apex new HttpMock() .whenPostOn('/api/v1/users') .body('{"id": "456", "created": true}') .contentTypeJson() .statusCodeCreated() .header('Location', '/api/v1/users/456') .mock(); ``` ### Response #### Success Response (201) - **body** (String) - The response body. - **contentType** (String) - The content type of the response. - **statusCode** (Integer) - The HTTP status code of the response. - **headers** (Map) - Custom headers to include in the response. #### Response Example ```json { "id": "456", "created": true } ``` ``` -------------------------------- ### 404 Not Found Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Resource not found. Use `statusCodeNotFound()` to set the status code to 404. ```APIDOC ## 404 Not Found ### Description Resource not found. ### Method GET ### Endpoint /api/users/999 ### Request Example ```apex new HttpMock() .whenGetOn('/api/users/999') .body('{"error": "User not found"}') .statusCodeNotFound() .mock(); ``` ### Response #### Error Response (404) - **body** (string) - JSON string representing the error body. ``` -------------------------------- ### 200 OK Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Standard success response. Use `statusCodeOk()` to set the status code to 200. ```APIDOC ## 200 OK ### Description Standard success response. ### Method GET ### Endpoint /api/users ### Request Example ```apex new HttpMock() .whenGetOn('/api/users') .body('{"users": []}') .statusCodeOk() .mock(); ``` ### Response #### Success Response (200) - **body** (string) - JSON string representing the response body. ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/CONTRIBUTING.md Stage all changes, commit them with a conventional commit message, and push to your remote branch. ```bash git add . git commit -m "feat: add support for XYZ feature" git push origin feature/my-awesome-feature ``` -------------------------------- ### Specify Redirect Location and Status Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/headers.md Use the `Location` header along with `statusCodeCreated()` to indicate a redirect to a newly created resource. This is common for POST requests that result in resource creation. ```apex new HttpMock() .whenPostOn('/api/users') .body('{"id": "123"}') .header('Location', '/api/users/123') .statusCodeCreated() .mock(); ``` -------------------------------- ### HTTP Methods Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/README.md Defines the HTTP methods that can be mocked. Each method allows specifying the endpoint to be mocked. ```APIDOC ## HTTP Methods ### Description These methods allow you to specify the HTTP method for the callout you want to mock. ### Methods - `whenGetOn(String endpointToMock)` - `whenPostOn(String endpointToMock)` - `whenPutOn(String endpointToMock)` - `whenPatchOn(String endpointToMock)` - `whenDeleteOn(String endpointToMock)` - `whenTraceOn(String endpointToMock)` - `whenHeadOn(String endpointToMock)` ``` -------------------------------- ### Mock HEAD and TRACE Endpoints with HttpMock Source: https://context7.com/beyond-the-cloud-dev/http-mock-lib/llms.txt Registers mock responses for HEAD and TRACE requests. Use this to simulate headers-only probes or diagnostic echo requests. ```apex new HttpMock() .whenHeadOn('/api/v1/users/123') .header('Content-Length', '512') .header('Last-Modified', 'Fri, 26 Dec 2025 00:00:00 GMT') .statusCodeOk() .mock(); ``` -------------------------------- ### Mock HEAD Request Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/http-methods.md Mock a HEAD request to retrieve only the headers for a resource. Specify the endpoint, a custom header, and an OK status code. ```apex new HttpMock() .whenHeadOn('/api/v1/users/123') .header('Content-Length', '1234') .statusCodeOk() .mock(); ``` -------------------------------- ### Configure Cache Control Headers Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/headers.md Set `Cache-Control` and `ETag` headers to manage response caching. This is crucial for optimizing performance and ensuring data freshness. ```apex new HttpMock() .whenGetOn('/api/static-data') .body('{"data": "cached"}') .header('Cache-Control', 'max-age=3600') .header('ETag', '"abc123"') .mock(); ``` -------------------------------- ### 403 Forbidden Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Access denied. Use `statusCodeForbidden()` to set the status code to 403. ```APIDOC ## 403 Forbidden ### Description Access denied. ### Method GET ### Endpoint /api/admin ### Request Example ```apex new HttpMock() .whenGetOn('/api/admin') .body('{"error": "Access denied"}') .statusCodeForbidden() .mock(); ``` ### Response #### Error Response (403) - **body** (string) - JSON string representing the error body. ``` -------------------------------- ### HEAD Request Mocking Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/http-methods.md Retrieve only the headers for a resource by mocking a HEAD request. Useful for checking resource metadata without the body. ```APIDOC ## HEAD /api/v1/users/123 ### Description Retrieve headers for a specific user resource. ### Method HEAD ### Endpoint /api/v1/users/123 ### Response #### Success Response (200 OK) - **Content-Length** (string) - The size of the resource body in bytes. ### Response Example ```json { "Content-Length": "1234" } ``` ``` -------------------------------- ### Mock a DELETE Endpoint Source: https://context7.com/beyond-the-cloud-dev/http-mock-lib/llms.txt Registers a mock response for an HTTP DELETE request. DELETE operations commonly return 204 No Content. ```apex new HttpMock() .whenDeleteOn('/api/v1/users/123') .statusCodeNoContent() .mock(); Test.startTest(); HttpResponse response = new TestApi().makeCallout('DELETE', '/api/v1/users/123'); Test.stopTest(); Assert.areEqual(204, response.getStatusCode()); Assert.areEqual(1, HttpMock.requestsTo('/api/v1/users/123').deletex()); ``` -------------------------------- ### Header Method Source: https://context7.com/beyond-the-cloud-dev/http-mock-lib/llms.txt Adds arbitrary headers to the mocked response, supporting multiple headers and underlying content type methods. ```APIDOC ## Header Method ### Description Adds an arbitrary header to the mocked response. This method can be chained multiple times to set multiple headers and also underlies the `contentType*()` convenience methods. ### Method Signature `header(String key, String value)` ### Parameters - **key** (String) - The name of the header. - **value** (String) - The value of the header. ### Request Example ```apex new HttpMock() .whenGetOn('/api/v1/items') .body('{"items": [], "total": 0}') .contentTypeJson() .statusCodeOk() .header('X-Total-Count', '0') .header('X-Page-Number', '1') .header('X-Page-Size', '20') .header('X-RateLimit-Limit', '100') .header('X-RateLimit-Remaining', '95') .header('Cache-Control', 'no-cache, no-store') .mock(); ``` ### Response Example (Response headers will include `X-Total-Count: 0`, `X-Page-Number: 1`, `X-Page-Size: 20`, `X-RateLimit-Limit: 100`, `X-RateLimit-Remaining: 95`, and `Cache-Control: no-cache, no-store`.) ``` -------------------------------- ### Headers Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/index.md Add custom headers to your mocked responses. ```APIDOC ## Headers ### `header(String key, String value)` Adds a custom header to the response with the specified key and value. ``` -------------------------------- ### Load Response Body from Static Resource with HttpMock Source: https://context7.com/beyond-the-cloud-dev/http-mock-lib/llms.txt Loads the response body from a named Salesforce Static Resource. Ideal for large or complex payloads. Throws `StaticResourceNotFoundException` if the resource does not exist. ```apex // Static Resource "UsersResponseMock" contains: // [{"id":"1","name":"Alice"},{"id":"2","name":"Bob"}] new HttpMock() .whenGetOn('/api/v1/users') .staticResource('UsersResponseMock') .contentTypeJson() .statusCodeOk() .mock(); ``` ```apex Exception caughtEx; try { new HttpMock() .whenGetOn('/api/v1/users') .staticResource('NonExistentResource') .mock(); } catch (Exception e) { caughtEx = e; } Assert.isNotNull(caughtEx); Assert.areEqual('Static Resource "NonExistentResource" not found.', caughtEx.getMessage()); ``` -------------------------------- ### Mock Plain Text Response Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/content-types.md Use `contentTypePlainText()` to set the Content-Type header to `text/plain` for simple text responses. ```apex new HttpMock() .whenGetOn('/api/status') .body('Service is running') .contentTypePlainText() .mock(); ``` -------------------------------- ### Mock POST Request with 501 Not Implemented Status Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Use `statusCodeNotImplemented()` to mock a response indicating that the server does not support the functionality required to fulfill the request. ```apex new HttpMock() .whenPostOn('/api/v2/feature') .body('{"error": "Not implemented"}') .statusCodeNotImplemented() .mock(); ``` -------------------------------- ### PUT Request Mocking Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/http-methods.md Update or replace existing resources by mocking a PUT request. Define the request body and success status code. ```APIDOC ## PUT /api/v1/users/123 ### Description Update or replace an existing user resource. ### Method PUT ### Endpoint /api/v1/users/123 ### Request Body - **id** (string) - Required - The ID of the user to update. - **updated** (boolean) - Indicates the update status. ### Request Example ```json { "id": "123", "updated": true } ``` ### Response #### Success Response (200 OK) - **id** (string) - The ID of the updated user. - **updated** (boolean) - Indicates the update status. ### Response Example ```json { "id": "123", "updated": true } ``` ``` -------------------------------- ### Mock PUT and PATCH Endpoints Source: https://context7.com/beyond-the-cloud-dev/http-mock-lib/llms.txt Registers mock responses for HTTP PUT (full-replace) and PATCH (partial-update) requests using the same fluent pattern. ```apex new HttpMock() .whenPutOn('/api/v1/users/123') .body('{"id": "123", "name": "Jane Doe", "updated": true}') .statusCodeOk() .mock(); new HttpMock() .whenPatchOn('/api/v1/users/123') .body('{"name": "Jane Doe"}') .statusCodeOk() .mock(); Test.startTest(); HttpResponse putResponse = new TestApi().makeCallout('PUT', '/api/v1/users/123'); HttpResponse patchResponse = new TestApi().makeCallout('PATCH', '/api/v1/users/123'); Test.stopTest(); Assert.areEqual(200, putResponse.getStatusCode()); Assert.areEqual(200, patchResponse.getStatusCode()); ``` -------------------------------- ### 204 No Content Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/status-codes.md Success with no response body. Use `statusCodeNoContent()` to set the status code to 204. ```APIDOC ## 204 No Content ### Description Success with no response body. ### Method DELETE ### Endpoint /api/users/123 ### Request Example ```apex new HttpMock() .whenDeleteOn('/api/users/123') .statusCodeNoContent() .mock(); ``` ``` -------------------------------- ### Mock JSON Response Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/content-types.md Use `contentTypeJson()` to set the Content-Type header to `application/json`. This is the default content type. ```apex new HttpMock() .whenGetOn('/api/users') .body('{"users": []}') .contentTypeJson() .mock(); ``` -------------------------------- ### Add Custom HTTP Headers Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/headers.md Use the `.header()` method to add custom headers to your mocked responses. This is useful for simulating API behavior or providing metadata. ```apex new HttpMock() .whenGetOn('/api/users') .body('{"users": []}') .header('X-Total-Count', '42') .header('X-Page-Number', '1') .mock(); ``` -------------------------------- ### After: Request Count API Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/release.md This demonstrates the new `requestsTo()` API for asserting request counts, introduced in version 1.2.0. It offers a more fluent and readable syntax. ```apex Assert.areEqual(2, HttpMock.requestsTo('/api/v1').get()); ``` -------------------------------- ### Mock CSV Response Source: https://github.com/beyond-the-cloud-dev/http-mock-lib/blob/main/website/api/content-types.md Use `contentTypeCsv()` to set the Content-Type header to `text/csv` for returning data in CSV format. ```apex new HttpMock() .whenGetOn('/api/export/users.csv') .body('id,name,email\n1,John,john@example.com') .contentTypeCsv() .mock(); ``` -------------------------------- ### Mock PUT and PATCH endpoints Source: https://context7.com/beyond-the-cloud-dev/http-mock-lib/llms.txt Registers mock responses for full-replace (PUT) or partial-update (PATCH) requests. Both follow the same fluent pattern. ```APIDOC ## whenPutOn(String endpoint) / whenPatchOn(String endpoint) ### Description Registers mock responses for full-replace (PUT) or partial-update (PATCH) requests. Both follow the same fluent pattern. ### Method PUT, PATCH ### Endpoint [endpoint] ### Parameters #### Path Parameters - **endpoint** (String) - Required - The endpoint path to mock. ### Request Example ```apex // PUT example new HttpMock() .whenPutOn('/api/v1/users/123') .body('{"id": "123", "name": "Jane Doe", "updated": true}') .statusCodeOk() .mock(); // PATCH example new HttpMock() .whenPatchOn('/api/v1/users/123') .body('{"name": "Jane Doe"}') .statusCodeOk() .mock(); ``` ### Response #### Success Response (200) - **body** (String) - The response body. - **statusCode** (Integer) - The HTTP status code of the response. #### Response Example ```json { "id": "123", "name": "Jane Doe", "updated": true } ``` ```