Sub topic 11
Mocking HTTP callouts from async code
This chapter assumes you can write a basic @IsTest class, know what a Queueable job does, and have seen Test.startTest and Test.stopTest used to run async work. It covers how to give async code a fake HTTP response in a test.
Why callouts need a mock
Apex tests cannot make real HTTP callouts. If async code calls an external service and the test provides no mock, the test fails with System.CalloutException: You have uncommitted work pending or, more commonly, Methods defined as TestMethod do not support Web service callouts.
The fix is to tell the platform which fake response to return. You do this with two pieces:
- A class that implements
HttpCalloutMockand returns a cannedHttpResponse. - A call to
Test.setMockbefore the code under test runs.
The code under test
A Queueable job that makes a callout must declare Database.AllowsCallouts. Without it, the callout fails in production and in the test.
public class CalloutJob implements Queueable, Database.AllowsCallouts {
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);
if (res.getStatusCode() == 200) {
update new Account(
Id = [SELECT Id FROM Account WHERE Name = 'Callout Test' LIMIT 1].Id,
Description = res.getBody()
);
}
}
}The mock class
@IsTest
private class StatusCalloutMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"status":"ok"}');
return res;
}
}The respond method receives the request your code built. You can inspect it, for example to check the endpoint or method, and return a different response for each.
Wiring the mock into the test
Call Test.setMock before Test.startTest, or at least before the async work is queued. Then enqueue the job inside the window.
@IsTest
private class CalloutJobTest {
@IsTest
static void jobStoresResponseBody() {
insert new Account(Name = 'Callout Test');
Test.setMock(HttpCalloutMock.class, new StatusCalloutMock());
Test.startTest();
System.enqueueJob(new CalloutJob());
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Name = 'Callout Test'];
Assert.areEqual('{"status":"ok"}', result.Description);
}
}The sequence is:
The job does not run until stopTest. The callout therefore happens at that point, and the mock answers it.
Common errors
| Symptom | Likely cause |
|---|---|
| `Methods defined as TestMethod do not support Web service callouts` | No call to `Test.setMock` before the callout ran. |
| Callout fails in the job even with a mock | The Queueable class does not implement `Database.AllowsCallouts`. |
| `You have uncommitted work pending` | The test did DML and then called out in the same transaction. Move DML before `startTest`, or put the callout in the async job as shown here. |
| Assertion sees old data | The test asserted before `stopTest`, or used a stale record variable instead of re-querying. |
Varying the response
To test error handling, create a second mock that returns a 500 status, or write one mock that branches on the request.
@IsTest
private class RoutingMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
if (req.getEndpoint().endsWith('/status')) {
res.setStatusCode(200);
res.setBody('{"status":"ok"}');
} else {
res.setStatusCode(404);
res.setBody('{"error":"not found"}');
}
return res;
}
}Exercise
A test enqueues a Queueable job that makes an HTTP callout, but it fails with "Methods defined as TestMethod do not support Web service callouts." The test calls Test.startTest, System.enqueueJob and Test.stopTest. What is missing, and where does it go?
Show answer
The test never called Test.setMock(HttpCalloutMock.class, new SomeMock()) with a class that implements HttpCalloutMock. It goes before the job runs, normally just before Test.startTest. The job runs at stopTest, so the mock must already be registered by then.