Sub topic 11
Mocking HTTP callouts
Apex tests cannot make real HTTP requests. This chapter shows how to replace the network with a mock, what to assert about the code that calls it, and which errors tend to appear.
This chapter assumes you can write an @IsTest class, use Assert methods, and call an external service with Http, HttpRequest, and HttpResponse. It also assumes you know Test.startTest and Test.stopTest and understand @TestSetup.
Why tests need a mock
If a test method reaches Http.send() with no mock registered, the platform stops it with this error:
System.CalloutException: Methods defined as TestMethod do not support Web service calloutsThis restriction is useful. Real endpoints are slow, can be down, and return different data over time. A mock gives the test a fixed response, so the test is fast and gives the same result every run. It also lets you produce failures, such as a 500 status or a malformed body, that are hard to trigger on demand from a real service.
You register a mock with Test.setMock(HttpCalloutMock.class, mockInstance). After that, every Http.send() in the same test transaction goes to your mock's respond method instead of the network.
The class under test
The examples use a small service that reads a temperature from a JSON API. It turns a non-200 status into a custom exception, so there are both a success path and an error path to test.
public class WeatherService {
public class WeatherException extends Exception {}
public static Integer getTemperature(String city) {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/weather?city='
+ EncodingUtil.urlEncode(city, 'UTF-8'));
req.setMethod('GET');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new WeatherException('Weather API returned ' + res.getStatusCode());
}
Map<String, Object> body =
(Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (Integer) body.get('temp');
}
}In production code you would normally use a Named Credential, with an endpoint such as callout:Weather_API/weather. The mocking technique is identical, because the mock intercepts the call whatever the endpoint is.
Writing a reusable mock
A mock is a class that implements HttpCalloutMock. The interface has one method, respond, which receives the HttpRequest your code built and returns the HttpResponse to use.
The mock below takes the status code and body in its constructor, so one class serves many tests. It also records the request it received and how many times it was called. That lets a test check what the code sent, not only what it returned.
@IsTest
public class WeatherMock implements HttpCalloutMock {
private Integer statusCode;
private String body;
public HttpRequest lastRequest;
public Integer callCount = 0;
public WeatherMock(Integer statusCode, String body) {
this.statusCode = statusCode;
this.body = body;
}
public HttpResponse respond(HttpRequest req) {
lastRequest = req;
callCount++;
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setStatusCode(statusCode);
res.setBody(body);
return res;
}
}Marking the class @IsTest keeps it out of your production code and excludes it from the code size limit. Public members of an @IsTest class are still usable from other test classes.
The success path
Register the mock before the callout runs, then call the code between startTest and stopTest. Assert on the return value and on the request the service built.
@IsTest
private class WeatherServiceTest {
@IsTest
static void returnsTemperatureFromResponse() {
WeatherMock mock = new WeatherMock(200, '{"temp":21}');
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
Integer temp = WeatherService.getTemperature('Oslo');
Test.stopTest();
Assert.areEqual(21, temp, 'Temperature should come from the mocked body');
Assert.areEqual(1, mock.callCount, 'Exactly one callout should be made');
Assert.areEqual('GET', mock.lastRequest.getMethod(), 'Request should be a GET');
Assert.isTrue(
mock.lastRequest.getEndpoint().contains('city=Oslo'),
'Endpoint should include the city parameter'
);
}
}The last two assertions matter. A mock returns what you told it to, whatever the request looked like. If the service sent the wrong method or dropped a parameter, only an assertion on lastRequest would catch it.
The error path
Use the same mock class with a failing status. This follows the negative-test pattern from earlier chapters: call the code, call Assert.fail if no exception occurs, and check the message in the catch block.
@IsTest
static void nonSuccessStatusThrows() {
Test.setMock(HttpCalloutMock.class, new WeatherMock(500, 'Server error'));
Test.startTest();
try {
WeatherService.getTemperature('Oslo');
Assert.fail('Expected WeatherException for a 500 response');
} catch (WeatherService.WeatherException e) {
Assert.areEqual('Weather API returned 500', e.getMessage(),
'Message should include the status code');
}
Test.stopTest();
}Add this method to WeatherServiceTest. Other failures to cover the same way are a 404, a 200 with an empty body, and a 200 with invalid JSON. Each one shows how your code behaves when the service misbehaves, which is the main reason to mock at all.
Choosing a mock style
| Approach | How it works | Best for |
|---|---|---|
| Custom class implementing `HttpCalloutMock` | You write `respond` yourself | Dynamic logic, checking the request, throwing exceptions |
| `StaticResourceCalloutMock` | Returns the body of a static resource, with status and headers you set | Large JSON or XML payloads kept out of test code |
| `MultiStaticResourceCalloutMock` | Maps endpoint URLs to static resources | Code that calls several endpoints with fixed responses |
| `Test.setMock` with a `WebServiceMock` | Mocks SOAP callouts made from generated WSDL classes | SOAP integrations, not `Http` |
StaticResourceCalloutMock needs a static resource containing the response, here named WeatherOk:
@IsTest
static void worksWithStaticResourceMock() {
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('WeatherOk');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json');
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
Integer temp = WeatherService.getTemperature('Oslo');
Test.stopTest();
Assert.isNotNull(temp, 'A temperature should be parsed from the resource');
}Several callouts in one test
Test.setMock takes one mock per interface type, and a later call replaces the earlier one. If your code calls two endpoints in the same transaction, one mock must handle both. Branch on the request inside respond:
@IsTest
public class RoutingMock implements HttpCalloutMock {
private Map<String, HttpResponse> responsesByPath = new Map<String, HttpResponse>();
public void addResponse(String path, Integer statusCode, String body) {
HttpResponse res = new HttpResponse();
res.setStatusCode(statusCode);
res.setBody(body);
responsesByPath.put(path, res);
}
public HttpResponse respond(HttpRequest req) {
for (String path : responsesByPath.keySet()) {
if (req.getEndpoint().contains(path)) {
return responsesByPath.get(path);
}
}
HttpResponse notFound = new HttpResponse();
notFound.setStatusCode(404);
notFound.setBody('No mock registered for ' + req.getEndpoint());
return notFound;
}
}The 404 fallback is deliberate. An unexpected endpoint produces a visible failure with a clear message, instead of a confusing null reference later.
Common errors
- Mock registered too late.
Test.setMockmust run before the firstHttp.send(). If it runs after, you get the "do not support Web service callouts" error. - Uncommitted work pending. A callout after DML in the same transaction fails with
You have uncommitted work pending. Please commit or rollback before calling out.In a test, create records in@TestSetup, which commits before the test method starts, and run only the callout inside the test. - Asserting only on the mock's own data. If the test checks that the result equals the string you put in the mock and nothing else, it proves little. Assert on what your code did with that data, such as parsed values, saved records, or thrown exceptions.
- Callouts in asynchronous code. A
Queueablethat calls out must implementDatabase.AllowsCallouts. In the test, register the mock, enqueue betweenstartTestandstopTest, and assert afterward. The queued job runs atstopTest, and the mock is used for its callouts. - Wrong interface type. SOAP callouts need
WebServiceMockand its ownTest.setMockcall. AnHttpCalloutMockdoes not intercept them.
What a good callout test proves
A thorough test suite for a callout class checks these things:
- The request is built correctly: method, endpoint, parameters, headers, and body.
- A normal response is parsed into the right result.
- Each error response, such as 4xx, 5xx, empty, or malformed, produces the intended behavior.
- A thrown
CalloutExceptionis handled as designed.
Code coverage will reach most of the class after the first test. The error-path tests are what show it handles failure.
Exercise
A test registers a mock with Test.setMock, then inserts an Account, then calls a service method that makes a callout. The test fails with "You have uncommitted work pending." How do you fix it without removing the DML from the test class?
Show answer
Move the Account creation into a @TestSetup method. Setup data is committed before each test method starts, so the callout inside the test method has no pending uncommitted work. The test method then queries the Account and calls the service between Test.startTest and Test.stopTest. Registering the mock earlier or later does not fix this error.
Exercise
Write the assertion that would catch a bug where WeatherService sends a POST instead of a GET, assuming the test uses the WeatherMock class from this chapter. Why does asserting only on the returned temperature miss this bug?
Show answer
Assert.areEqual('GET', mock.lastRequest.getMethod(), 'Request should be a GET'); The mock returns the same fake body whatever method the request used, so the returned temperature would still be 21 and the test would pass. Only an assertion on the captured request shows what the service actually sent.