Sub topic 2
The Http, HttpRequest, and HttpResponse classes
This chapter assumes you can read and write basic Apex classes and know what a @IsTest class is. It also assumes you know HTTP methods, status codes, and JSON. Every callout test in this tutorial depends on three built-in classes. A mock builds an HttpResponse, reads an HttpRequest, and stands in for Http.send. You need to know how each class behaves before you write a mock.
The three classes and their roles
Apex exposes HTTP through three classes in the System namespace. You don't need to import them.
| Class | Role | Typical members |
|---|---|---|
| `HttpRequest` | Describes what to send | `setEndpoint`, `setMethod`, `setHeader`, `setBody`, `setTimeout` |
| `Http` | Sends a request | `send(HttpRequest)` |
| `HttpResponse` | Describes what came back | `getStatusCode`, `getStatus`, `getHeader`, `getBody` |
Your code builds an HttpRequest, passes it to Http.send, and receives an HttpResponse. In a test, Http.send returns the response from your mock instead of contacting a server.
HttpRequest
An HttpRequest is a plain object. You create it with new HttpRequest() and configure it with setter methods. Nothing is sent until you pass it to Http.send.
The members you use most:
setEndpoint(String)sets the full URL, or a named credential reference such ascallout:Weather_API/forecast.setMethod(String)sets the verb:GET,POST,PUT,PATCH,DELETE, and so on. Use uppercase strings.setHeader(String name, String value)sets one header. Calling it again with the same name replaces the value.setBody(String)sets a text body.setBodyAsBlob(Blob)sets binary content.setTimeout(Integer)sets the timeout in milliseconds. The default is 10,000 (10 seconds). The maximum is 120,000.setCompressed(Boolean)compresses the request body with gzip when true.
Each setter has a matching getter: getEndpoint, getMethod, getHeader, getBody. These getters matter in tests. A mock receives the request in its respond method and can call them to decide what to return. A test can also use them to check what your code sent.
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/orders');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(new Map<String, Object>{ 'item' => 'Widget', 'qty' => 3 }));
req.setTimeout(30000);Http
Http has one method that matters, send(HttpRequest). It is synchronous. The call blocks until the response arrives or the timeout expires. Calling new Http() is cheap, so you don't need to cache the object.
send throws a System.CalloutException when no HTTP response arrives. Examples are an unreachable host, a timeout, or an endpoint your org hasn't authorized. A server that answers with an error status does not make send throw. A 404 or 500 comes back as a normal HttpResponse, and your code has to check the status itself. This is the most common source of untested error handling, and the "Testing error responses and failures" chapter returns to it.
The platform places several limits on callouts:
- A transaction can make at most 100 callouts.
- The cumulative timeout across all callouts in a transaction is 120 seconds.
- Request and response sizes are bounded by the heap limit: 6 MB for synchronous Apex and 12 MB for asynchronous Apex.
- The endpoint must be authorized, either through a Remote Site Setting or a named credential. An unauthorized endpoint raises a
CalloutExceptionat runtime.
HttpResponse
An HttpResponse holds what the server returned. The getters you use most:
getStatusCode()returns the numeric code, such as200.getStatus()returns the text, such asOK.getBody()returns the body as aString.getBodyAsBlob()returns it as aBlob.getHeader(String)returns one header value, ornullif the header is absent.getHeaderKeys()returns the header names.
HttpResponse also has setters: setStatusCode, setStatus, setBody, setBodyAsBlob, and setHeader. In production code you rarely call them. In a test they are the main tool, because a mock creates an HttpResponse from scratch and fills it with the values you want your code to see.
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setStatus('OK');
res.setHeader('Content-Type', 'application/json');
res.setBody('{"condition":"Sunny"}');The constructor takes no arguments, and a fresh object has no status code, no headers, and no body. Anything your code reads must be set explicitly. A mock that forgets setStatusCode returns an object whose getStatusCode() is 0, and your service code may then treat a successful call as a failure.
Reading the example service
The code under test throughout this tutorial uses all three classes:
public with sharing class WeatherService {
public class WeatherException extends Exception {}
public static String getCondition(String city) {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/weather?city=' + EncodingUtil.urlEncode(city, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new WeatherException('Unexpected status: ' + res.getStatusCode());
}
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (String) body.get('condition');
}
}Reading it as a test author, note what each line gives you to control or observe:
- The endpoint, method, and
Acceptheader are what you can verify on the outgoing request. new Http().send(req)is the seam where a mock takes over.getStatusCode()splits the code into a success path and an error path, so you need at least two mock responses.getBody()feeds the JSON parser, so the mock body must be valid JSON containing aconditionkey. A body without that key makesbody.get('condition')returnnull.
The code never touches the network except at send. That single point is why a mock can replace the whole remote service.
Seeing the classes work without a callout
The request and response classes are ordinary objects. You can create and inspect them in a test without any callout and without a mock. This is a good way to confirm how the getters behave before you write a real mock.
@IsTest
private class HttpClassesBehaviorTest {
@IsTest
static void requestGettersReturnWhatWasSet() {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/orders');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody('{"qty":3}');
Assert.areEqual('https://api.example.com/orders', req.getEndpoint());
Assert.areEqual('POST', req.getMethod());
Assert.areEqual('application/json', req.getHeader('Content-Type'));
Assert.areEqual('{"qty":3}', req.getBody());
}
@IsTest
static void responseGettersReturnWhatWasSet() {
HttpResponse res = new HttpResponse();
res.setStatusCode(404);
res.setStatus('Not Found');
res.setBody('{"error":"missing"}');
Assert.areEqual(404, res.getStatusCode());
Assert.areEqual('Not Found', res.getStatus());
Assert.isNull(res.getHeader('Content-Type'), 'An unset header reads as null');
Assert.isTrue(res.getBody().contains('missing'));
}
}Neither test calls Http.send, so neither needs a mock.
Common errors
These mistakes show up often when people first test callout code:
- Calling
sendin a test with no mock registered. The test fails with "Methods defined as TestMethod do not support Web service callouts". The next chapters explain why and how to fix it. - Assuming a non-2xx status throws.
sendreturns normally for 4xx and 5xx. If your code has no status check, an error body flows into your JSON parser and fails there instead. - Forgetting the status code in a hand-built response. An unset code reads as
0, which fails any== 200check. - Case-sensitive header names in comparisons.
getHeadermatches names as you set them, so compare consistently. Mocks and code should use the same spelling, such asContent-Type. - Reading the body as a
Stringfor binary data. UsegetBodyAsBlob()when the payload is a file or image.
Why this matters for the mock
The mock you write in the next chapters has one job. It receives an HttpRequest and returns an HttpResponse. Everything in this chapter is the vocabulary for that job. The request getters are what your mock reads, the response setters are what it fills in, and send is the call it intercepts.
Exercise
A service method calls new Http().send(req) and the remote server replies with status 503 and the body Service Unavailable. Does send throw an exception? Name one thing a hand-built HttpResponse in a mock must set so that your code sees that 503, and say what getStatusCode() returns if you forget it.
Show answer
No. send returns normally with an HttpResponse for any status the server returns, including 503. It throws CalloutException only when no response arrives, for example on a timeout or an unauthorized endpoint. A mock must call setStatusCode(503). If it doesn't, getStatusCode() returns 0, so code that checks for 200 or 503 will not see the intended value.
Exercise
Write a snippet that builds an HttpRequest for a PUT to https://api.example.com/items/7 with a JSON body {"name":"Bolt"} and a 20-second timeout.
Show answer
HttpRequest req = new HttpRequest(); req.setEndpoint('https://api.example.com/items/7'); req.setMethod('PUT'); req.setHeader('Content-Type', 'application/json'); req.setBody('{"name":"Bolt"}'); req.setTimeout(20000);