Sub topic 1
Why Apex Tests Cannot Make Real Callouts
Apex tests run in an isolated Salesforce context. They cannot contact an external HTTP service. This keeps tests deterministic, prevents tests from changing outside systems, and avoids depending on network availability. Instead, a test supplies a mock response.
Prerequisites
This chapter assumes basic Apex classes, @IsTest methods, HTTP methods and status codes, and JSON syntax. You should also know how to run an Apex test.
The HTTP classes
Apex uses three classes for an HTTP callout:
HttpRequestdescribes the outgoing request, including its endpoint, method, headers, and body.Httpsends the request withsend().HttpResponsecontains the returned status code, headers, and body.
Keep callout code in a small service class. This gives the test one clear entry point and makes the external boundary easy to replace.
public with sharing class WeatherService {
public class WeatherException extends Exception {}
public static String getCondition(String city) {
HttpRequest request = new HttpRequest();
request.setEndpoint(
'https://api.example.com/weather?city=' +
EncodingUtil.urlEncode(city, 'UTF-8')
);
request.setMethod('GET');
request.setHeader('Accept', 'application/json');
HttpResponse response = new Http().send(request);
if (response.getStatusCode() != 200) {
throw new WeatherException(
'Unexpected status: ' + response.getStatusCode()
);
}
Map<String, Object> body =
(Map<String, Object>) JSON.deserializeUntyped(response.getBody());
return (String) body.get('condition');
}
}The service checks the status before parsing the body. That prevents an error response from being treated as a successful JSON result.
Implementing `HttpCalloutMock`
HttpCalloutMock is an interface, which is a contract requiring a respond method. Salesforce calls this method instead of making the real request after the test registers the mock.
@IsTest
public class WeatherServiceMock implements HttpCalloutMock {
private Integer statusCode;
private String body;
public WeatherServiceMock(Integer statusCode, String body) {
this.statusCode = statusCode;
this.body = body;
}
public HttpResponse respond(HttpRequest request) {
HttpResponse response = new HttpResponse();
response.setStatusCode(statusCode);
response.setHeader('Content-Type', 'application/json');
response.setBody(body);
return response;
}
}The mock receives the actual HttpRequest, so it can later verify the endpoint or choose a response based on the request. A test registers it with Test.setMock(HttpCalloutMock.class, mock) before calling WeatherService.
Exercise
Why must a test register an HttpCalloutMock before calling code that uses Http.send()?
Show answer
Salesforce uses the registered mock to intercept the callout and return a controlled HttpResponse instead of contacting an external service.