Apex Callouts and Test.setMock: Testing an External REST Integration Without Live Credentials
0 reputation · 09 Aug 2025, 20:23 UTC
0 reputation · 09 Aug 2025, 20:23 UTC
An Apex service class integrates with an external REST API through HttpRequest and HttpResponse, and the integration needs test coverage in an environment where production credentials and live endpoints are unavailable. The documented mechanism is Test.setMock with an HttpCalloutMock implementation, which intercepts the callout so no real request leaves the org.
The unresolved design point is how to structure the mock layer when the service contacts more than one endpoint, or when different methods expect different response payloads. It is also unclear which runtime rules remain in force once a mock is registered, such as whether endpoints must still be whitelisted and whether test-context callouts consume the organization's concurrent callout or API limits.
HttpCalloutMock class branch on the request endpoint and method, or should each callout path receive its own mock implementation?31775 reputation · 10 Aug 2025, 03:57 UTC
Test.setMock method is the standard mechanism for intercepting HttpRequest objects. This allows you to simulate various API behaviors without requiring live credentials or Remote Site Settings in your test environment.
HttpCalloutMock class. Inside the respond method, you use request.getEndpoint() and request.getMethod() to determine which HttpResponse to return. This is often preferred for simple integrations where the logic remains clear and centralized.GetAccountMock, PostOrderMock). This is cleaner for complex services where the response payloads vary significantly, as it prevents a single mock class from becoming a massive, nested conditional block.There are common misconceptions regarding how mocked calls interact with Salesforce platform constraints. Here are the confirmed runtime behaviors:
To implement a branching mock, use a structure similar to this:
public class MyServiceMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest request) {
HttpResponse response = new HttpResponse();
if (request.getEndpoint().contains('//v1/users/')) {
response.setStatusCode(200);
response.setBody('{"name": "Test User"}');\n } else if (request.getMethod() == 'POST') {
response.setStatusCode(201);
response.setBody('{"status": "success"}');
}
response.setHeader('Content-Type', 'application/json');
return response;
}
}
Note: If your service class relies on specific headers for authentication, ensure your mock also sets or validates those headers to avoid logic failures in the code under test.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.