Sub topic 11
Mocking HTTP callouts from async code
This chapter assumes you can write an @IsTest class, that you know the Http, HttpRequest and HttpResponse classes at a basic level, and that you have seen the startTest/stopTest window from the earlier chapters. Here you will test async code that calls an external service without making a real call.
Why tests need a mock
Apex tests are not allowed to make real HTTP callouts. If code under test calls Http.send and no mock is registered, the test fails with the error "Methods defined as TestMethod do not support Web service callouts". Real callouts would make tests slow and flaky. They would also make results depend on a system you don't control.
The fix is to tell the platform what response to return. You write a class that implements HttpCalloutMock, then register an instance with Test.setMock. When the code calls Http.send, the platform skips the network and calls your mock's respond method instead.
Async code adds one wrinkle. The callout happens inside a job that doesn't run until Test.stopTest(). The mock must therefore be registered before that point, and the assertions must come after it.
Make the async code callout-capable first
A mock only helps if the production code is allowed to call out. Each async type has its own rule:
| Async type | What it needs to make callouts |
|---|---|
| `@future` method | `@future(callout=true)` |
| Queueable | The class also implements `Database.AllowsCallouts` |
| Batch Apex | The class also implements `Database.AllowsCallouts` |
| Schedulable | Not allowed directly. Enqueue a Queueable or batch that allows callouts. |
If you forget the marker, the test fails with a callout error even though the mock is registered. The mock does not bypass the marker.
The class under test
This Queueable job calls a status service and writes the result to an account. The endpoint is hard-coded to keep the example short. In production code, use a Named Credential so the endpoint and authentication live in configuration.
public class CalloutJob implements Queueable, Database.AllowsCallouts {
private Id accountId;
public CalloutJob(Id accountId) {
this.accountId = accountId;
}
public void execute(QueueableContext context) {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/status');
req.setMethod('GET');
HttpResponse res = new Http().send(req);
String description;
if (res.getStatusCode() == 200) {
Map<String, Object> body =
(Map<String, Object>) JSON.deserializeUntyped(res.getBody());
description = 'Status: ' + (String) body.get('status');
} else {
description = 'Callout failed: ' + res.getStatusCode();
}
update new Account(Id = accountId, Description = description);
}
}A reusable mock
The mock below takes the status code and body in its constructor. One class can then play both the success case and the failure case.
@IsTest
public class StatusCalloutMock implements HttpCalloutMock {
private Integer statusCode;
private String body;
public StatusCalloutMock(Integer statusCode, String body) {
this.statusCode = statusCode;
this.body = body;
}
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setStatusCode(statusCode);
res.setBody(body);
return res;
}
}The @IsTest annotation keeps the class out of your org's code size limit. It also keeps the class out of production use.
Where each step goes
The order inside the test method matters. The sequence is:
- Create the test data with DML.
- Register the mock with
Test.setMock. - Call
Test.startTest(). - Start the async work.
- Call
Test.stopTest(). - Re-query the record and assert.
The test class
This test covers the success path and a server error.
@IsTest
private class CalloutJobTest {
@IsTest
static void successfulCalloutUpdatesAccount() {
Account a = new Account(Name = 'Callout Test');
insert a;
Test.setMock(
HttpCalloutMock.class,
new StatusCalloutMock(200, '{"status":"ok"}')
);
Test.startTest();
System.enqueueJob(new CalloutJob(a.Id));
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Status: ok', result.Description);
}
@IsTest
static void serverErrorIsRecorded() {
Account a = new Account(Name = 'Callout Error Test');
insert a;
Test.setMock(
HttpCalloutMock.class,
new StatusCalloutMock(500, '{"error":"unavailable"}')
);
Test.startTest();
System.enqueueJob(new CalloutJob(a.Id));
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Callout failed: 500', result.Description);
}
}The test inserts the account before the window, so the account exists when the job runs. The job runs in its own transaction at stopTest, so the setup DML does not trigger the "uncommitted work pending" error that blocks a callout after DML in the same transaction.
Registering the mock before or inside the window
You can call Test.setMock before Test.startTest() or inside the window, as long as it comes before stopTest(). Putting it before startTest() is a good habit. Your setup stays in one block, and the window contains only the code under test.
Testing `@future(callout=true)` methods
The pattern is identical. Register the mock, open the window, call the future method, close the window, and assert. A minimal future method that uses the same mock might look like this:
public class StatusService {
@future(callout=true)
public static void refresh(Id accountId) {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/status');
req.setMethod('GET');
HttpResponse res = new Http().send(req);
update new Account(Id = accountId, Description = 'HTTP ' + res.getStatusCode());
}
}Its test calls StatusService.refresh(a.Id) between startTest and stopTest, and the same StatusCalloutMock supplies the response. Future methods take only primitive arguments, so the method receives an Id and not an Account record.
Testing batch jobs that call out
A batch class that implements Database.AllowsCallouts can make a callout in execute. In a test, only one execute call runs, so keep the data to a single scope. The mock is used for every callout in that call, so it is a good place to check that your code makes one callout per record or one per scope, as you intended.
Several endpoints, one mock
Test.setMock registers one mock per interface type. Calling it a second time with HttpCalloutMock.class replaces the first mock. If your async code calls two endpoints, you have two options:
- Write one mock that branches on
req.getEndpoint()andreq.getMethod(). - Use the platform's
MultiStaticResourceCalloutMock, which maps endpoints to static resources.
A branching mock stays readable if each branch is short:
@IsTest
public class RoutingCalloutMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
if (req.getEndpoint().endsWith('/status')) {
res.setStatusCode(200);
res.setBody('{"status":"ok"}');
} else if (req.getEndpoint().endsWith('/token')) {
res.setStatusCode(200);
res.setBody('{"token":"abc123"}');
} else {
res.setStatusCode(404);
res.setBody('{}');
}
return res;
}
}The fallback 404 is deliberate. If the code calls an endpoint you did not expect, the test fails visibly instead of silently receiving a success response.
For responses that are long JSON documents, StaticResourceCalloutMock loads the body from a static resource file. That keeps large payloads out of your Apex code.
Asserting on the request, not only the response
A mock can also check what the code sent. Because respond receives the HttpRequest, you can throw an exception from the mock when the request is wrong, or record it in a static field for the test to inspect.
@IsTest
public class RecordingCalloutMock implements HttpCalloutMock {
public static List<HttpRequest> requests = new List<HttpRequest>();
public HttpResponse respond(HttpRequest req) {
requests.add(req);
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"status":"ok"}');
return res;
}
}After stopTest, the test can assert on RecordingCalloutMock.requests.size() and on requests[0].getMethod(). Static fields keep their values across the async boundary within a test, so this works for jobs that run at stopTest.
Common errors
- "Methods defined as TestMethod do not support Web service callouts." No mock was registered, or
Test.setMockran after the job had already executed. Move it beforestopTest(). - A callout error even with a mock. The async class lacks
Database.AllowsCallouts, or the future method lackscallout=true. - A callout fails after DML in the same transaction. This happens when your test makes a synchronous callout after inserting data. Run the callout in an async job, or make the callout before the DML.
- The assertion sees the old value. The test asserted before
stopTest(), or it checked a variable that was loaded before the job ran. Re-query the record. - A mock that returns the same body for every endpoint. The code under test appears to work because every call gets a success response. Use a routing mock with a failing default.
Exercise
A Queueable job implements Queueable but not Database.AllowsCallouts. Its test registers a mock with Test.setMock before startTest and enqueues the job inside the window. What happens at stopTest, and what is the fix?
Show answer
The job runs at stopTest and the callout fails with an error, because the mock does not override the rule that async code must be marked as callout-capable. The fix is to change the class declaration to implement both Queueable and Database.AllowsCallouts. The test then runs the job against the mock.
Exercise
Your async code calls both /status and /token. You call Test.setMock twice, once with a status mock and once with a token mock, both for HttpCalloutMock.class. Why does the /status call fail, and how do you fix it?
Show answer
The second Test.setMock call replaces the first, so only the token mock is active and it answers every callout. Fix it by writing one mock that branches on req.getEndpoint(), or by using MultiStaticResourceCalloutMock, and register that single mock once.