Sub topic 12
Testing asynchronous callouts
Callouts often run outside the user's transaction, in @future methods, Queueable jobs, and Batch Apex. This chapter shows how to test them with the same HttpCalloutMock you used earlier, and how to assert on what the job actually did.
This chapter assumes you can write a mock class, register it with Test.setMock, and use Test.startTest and Test.stopTest. It also assumes you know the WeatherService and WeatherServiceMock classes from earlier chapters.
How async Apex behaves in a test
In production, an async job is queued and runs later in its own transaction. In a test, the platform does not run queued work in the background. It holds the work until Test.stopTest() is called, then runs it synchronously, so your assertions can follow on the next line.
Two rules follow from this:
- Call
Test.setMockbefore the job runs. Setting it beforeTest.startTest()is the safest habit. - Assert after
Test.stopTest(). Before that point the job has not run.
Which async types can make callouts
Each async type needs an explicit opt-in before it can make a callout.
| Async type | Opt-in for callouts | When it runs in a test |
|---|---|---|
| `@future` method | `@future(callout=true)` | At `Test.stopTest()` |
| Queueable | `implements Database.AllowsCallouts` | At `Test.stopTest()` |
| Batch Apex | `implements Database.AllowsCallouts` | At `Test.stopTest()`, for one batch of up to 200 records |
| Schedulable | The scheduled class cannot call out directly. It enqueues a Queueable or batch that does. | At `Test.stopTest()` |
If you forget the opt-in, the production code fails with a callout error. A test that exercises the job with a mock will catch it.
Make the job produce something you can assert
The WeatherSyncJob from the plan only calls System.debug. A test of that job can assert almost nothing, which is why the earlier example ends with Assert.isTrue(true, ...). That assertion passes whether or not the job did anything useful.
A job should leave an observable result. The version below writes the condition to the Description field of an Account, and records a fallback value when the service fails.
public class WeatherSyncJob implements Queueable, Database.AllowsCallouts {
private Id accountId;
private String city;
public WeatherSyncJob(Id accountId, String city) {
this.accountId = accountId;
this.city = city;
}
public void execute(QueueableContext ctx) {
Account acc = new Account(Id = accountId);
try {
acc.Description = WeatherService.getCondition(city);
} catch (WeatherService.WeatherException e) {
acc.Description = 'Unavailable';
}
update acc;
}
}The job makes the callout first and does its DML afterward. This order matters, as the section on DML ordering below explains.
Testing a Queueable job
@IsTest
private class WeatherSyncJobTest {
@IsTest
static void storesConditionOnSuccess() {
Account acc = new Account(Name = 'Acme');
insert acc;
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{"condition":"Rain"}'));
Test.startTest();
System.enqueueJob(new WeatherSyncJob(acc.Id, 'Oslo'));
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :acc.Id];
Assert.areEqual('Rain', result.Description, 'Job should store the mocked condition');
}
@IsTest
static void storesFallbackOnServerError() {
Account acc = new Account(Name = 'Acme');
insert acc;
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(500, '{"error":"boom"}'));
Test.startTest();
System.enqueueJob(new WeatherSyncJob(acc.Id, 'Oslo'));
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :acc.Id];
Assert.areEqual('Unavailable', result.Description, 'Job should record the fallback value');
}
}The test inserts the Account before Test.startTest(). That insert belongs to the test's own transaction. The job runs in a separate transaction at Test.stopTest(), so the earlier DML does not block its callout.
Testing a future method
A future method takes only primitive arguments (or collections of them), so pass an Id and a String. It is also static and returns void, so the only thing to assert is its side effect.
public class WeatherFuture {
@future(callout=true)
public static void syncAccount(Id accountId, String city) {
String condition = WeatherService.getCondition(city);
update new Account(Id = accountId, Description = condition);
}
}@IsTest
private class WeatherFutureTest {
@IsTest
static void futureStoresCondition() {
Account acc = new Account(Name = 'Acme');
insert acc;
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{"condition":"Snow"}'));
Test.startTest();
WeatherFuture.syncAccount(acc.Id, 'Oslo');
Test.stopTest();
Assert.areEqual(
'Snow',
[SELECT Description FROM Account WHERE Id = :acc.Id].Description,
'Future method should store the mocked condition'
);
}
}This version has no try/catch. If the mock returned 500, WeatherService would throw. An unhandled exception in async code can surface as a failure of the test at Test.stopTest(), so test an error path by catching it in the job, as WeatherSyncJob does, or by asserting on the exception.
Batch and scheduled jobs
A batch class that makes callouts implements both Database.Batchable<SObject> and Database.AllowsCallouts. In a test, call Database.executeBatch between startTest and stopTest. Two limits shape what you can test:
- Only one batch runs in a test. The scope you pass must be 200 records or fewer, and the test inserts data to match. A test cannot confirm that a 5,000-record job loops correctly.
- Every record in the scope that triggers a callout gets the same mock response, unless you use a routing mock.
For a Schedulable class, call System.schedule inside the start and stop pair. The scheduled class runs at Test.stopTest(). If it enqueues a Queueable or batch, that work runs too.
DML ordering in async code
The platform rejects a callout if the same transaction has already made DML and not yet committed it. The error reads "You have uncommitted work pending. Please commit or rollback before calling out."
This is the reason WeatherSyncJob calls the service first and updates the record second. If it updated the Account first and then called the service, the callout would fail. The test would show this failure only if your mock is registered and the job runs, which is another reason to test through Test.stopTest() and not call execute by hand.
Chained jobs and other gotchas
- Chaining. A Queueable that enqueues another Queueable cannot do so in a test. The platform limits the stack depth to one, so the nested
System.enqueueJobthrows. A common workaround is to guard the chained call withif (!Test.isRunningTest()), and then to test the second job by enqueuing it directly. Newer API versions also offerSystem.AsyncInfoto check the stack depth. Check the current Apex reference for your org's version. - Missing mock. If a job reaches a callout without a registered mock, the test fails with "Methods defined as TestMethod do not support Web service callouts." In async code this often means
Test.setMockran afterTest.stopTest(). - Mock set too early is fine. The mock stays registered for the rest of the test method, so one
Test.setMockcall covers any async job started afterward. - Several callouts. If a job calls two endpoints, use the
RoutingMockfrom the earlier chapter and assert on the recorded requests afterstopTest. - Limits.
Test.startTest()gives the code between the start and stop calls a fresh set of governor limits. The async job itself gets its own limits again when it runs atstopTest. - Asserting async work. Never assert on a result before
Test.stopTest(). The query will return the old value, and the test will fail even though the code is correct.
Checklist for an async callout test
- Create and insert test data before
Test.startTest(). - Register the mock with
Test.setMock. - Call
Test.startTest(), start the async work, then callTest.stopTest(). - Query for the side effect and assert on it.
- Repeat with an error response and assert on the fallback behavior.
Exercise
A test enqueues a Queueable that makes a callout. It calls Test.setMock after Test.stopTest() and then queries the result. The test fails with "Methods defined as TestMethod do not support Web service callouts." What is wrong, and how do you fix it?
Show answer
The job runs synchronously at Test.stopTest(), so the callout happens before the mock is registered. Move Test.setMock before Test.startTest() (or at least before Test.stopTest()), and keep the query and assertions after Test.stopTest().
Exercise
Why does WeatherSyncJob call WeatherService.getCondition before it runs update acc? What error would you see if the order were reversed?
Show answer
A callout is not allowed after uncommitted DML in the same transaction. If the update came first, the callout would fail with "You have uncommitted work pending. Please commit or rollback before calling out." Doing the callout first avoids the error.