Sub topic 12
Testing chained Queueable jobs
This chapter assumes you can write a basic @IsTest class, that you know how Test.startTest and Test.stopTest run a Queueable job at stopTest, and that you have seen System.enqueueJob before. It covers one case where the test window behaves differently: a Queueable job that enqueues another Queueable job.
What chaining is
Chaining means a Queueable job calls System.enqueueJob from inside its own execute method. Production code uses it to work through a long list one step at a time, or to run steps in a fixed order. Each job in the chain runs in its own transaction with its own governor limits.
In production, an executing job can add only one child job. Tests are stricter.
The test-context rule
Apex tests can't chain Queueable jobs. The job you enqueue between startTest and stopTest runs at stopTest. If its execute method then calls System.enqueueJob, the platform throws a System.AsyncException (for example, "Maximum stack depth has been reached"). The test fails even though the same code works in production.
The test context runs only the first job and refuses to start the chain. You have two ways to deal with this:
- Stop the chain in tests with a guard, so the first job doesn't try to enqueue a child.
- Test each link of the chain separately, so no single test needs more than one job to run.
The best approach combines both.
A chained job that is testable
The job below processes a list of account IDs, one account per job. After it updates the first account, it builds a job for the remaining IDs and enqueues it.
The decision about what to chain lives in buildNext, a separate method. The test can call buildNext directly and check the decision without running the chain. The Test.isRunningTest() guard keeps the real enqueue from happening inside a test.
public class ChainedAccountJob implements Queueable {
private List<Id> remainingIds;
public ChainedAccountJob(List<Id> remainingIds) {
this.remainingIds = remainingIds;
}
public void execute(QueueableContext context) {
update new Account(Id = remainingIds[0], Description = 'Processed');
Queueable next = buildNext();
if (next != null && !Test.isRunningTest()) {
System.enqueueJob(next);
}
}
@TestVisible
private Queueable buildNext() {
if (remainingIds.size() <= 1) {
return null;
}
List<Id> rest = new List<Id>();
for (Integer i = 1; i < remainingIds.size(); i++) {
rest.add(remainingIds[i]);
}
return new ChainedAccountJob(rest);
}
}buildNext returns null when the last ID is being processed. This is the stop condition of the chain. A chain without a reliable stop condition keeps enqueueing jobs until it hits an org limit, so test it explicitly.
Three tests, three questions
One chain raises three separate questions:
| Question | How to test it |
|---|---|
| Does the first job do its own work? | Enqueue it between `startTest` and `stopTest`, then re-query. |
| Does the job choose the right next step? | Call `buildNext` directly and check what it returns. |
| Does a later link do its work? | Create that job yourself and call `execute` on it. |
@IsTest
private class ChainedAccountJobTest {
@TestSetup
static void makeData() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 3; i++) {
accounts.add(new Account(Name = 'Chain ' + i));
}
insert accounts;
}
private static List<Id> accountIdsByName() {
List<Id> ids = new List<Id>();
for (Account a : [SELECT Id FROM Account WHERE Name LIKE 'Chain %' ORDER BY Name]) {
ids.add(a.Id);
}
return ids;
}
@IsTest
static void firstJobProcessesOnlyItsAccount() {
List<Id> ids = accountIdsByName();
Test.startTest();
System.enqueueJob(new ChainedAccountJob(ids));
Test.stopTest();
Map<Id, Account> byId = new Map<Id, Account>(
[SELECT Description FROM Account WHERE Id IN :ids]
);
Assert.areEqual('Processed', byId.get(ids[0]).Description);
Assert.isNull(byId.get(ids[1]).Description);
Assert.isNull(byId.get(ids[2]).Description);
}
@IsTest
static void jobChoosesNextStep() {
List<Id> ids = accountIdsByName();
Queueable next = new ChainedAccountJob(ids).buildNext();
Assert.isTrue(next instanceof ChainedAccountJob);
Queueable last = new ChainedAccountJob(new List<Id>{ ids[2] }).buildNext();
Assert.isNull(last);
}
@IsTest
static void laterLinkDoesItsWork() {
List<Id> ids = accountIdsByName();
Test.startTest();
new ChainedAccountJob(new List<Id>{ ids[1], ids[2] }).execute(null);
Test.stopTest();
Account second = [SELECT Description FROM Account WHERE Id = :ids[1]];
Assert.areEqual('Processed', second.Description);
}
}The test data is created in a @TestSetup method, so it exists before any test window opens. The first test checks that the account at index 0 was processed and the other two were not. That proves the chain stopped after one link, and the test did not need a second job to run.
The third test calls execute(null) directly. This is an ordinary synchronous method call, so it needs no queue. Passing null for the QueueableContext is safe only because this execute never reads the context. If your job calls context.getJobId(), enqueue it through System.enqueueJob between startTest and stopTest instead.
Working through the whole chain
Each test above covers one link. To cover the whole chain, walk it by hand. Create the job for the full list, call buildNext, and repeat on what it returns until it gives null. This catches off-by-one mistakes in the list slicing without any async machinery.
The buildNext method returns a Queueable, so a test can only check its type. To check which IDs are left, expose a @TestVisible getter for the list or return the concrete class. Do that only if the slicing logic is complex enough to need it.
Guarding with Test.isRunningTest
The guard in execute is a small compromise, and you should know its cost:
- The line
System.enqueueJob(next)never runs in a test, so it counts as uncovered. A single uncovered line is usually acceptable, but check your coverage rules. - Production behavior and test behavior differ by one condition. Keep the guard on the enqueue line only. Don't put business logic behind
Test.isRunningTest(), or your tests stop describing production. - If you leave out the guard, any test that runs a job with a successor fails with the
AsyncExceptiondescribed earlier.
Related limits worth remembering
- A test method gets one
startTest/stopTestpair. You can't run job 1, assert, then open a new window for job 2. - Several root jobs enqueued inside the same window all run at
stopTest. Each of them is still subject to the no-chaining rule. - Enqueued jobs also count against the per-transaction limit on
System.enqueueJobcalls. In a synchronous transaction that limit is 50, so a loop that enqueues many jobs fails in a test just as it does in production.
Summary
- The test window runs the first Queueable job at
stopTest, and that job can't enqueue a child. - Guard the enqueue with
Test.isRunningTest(), or anAsyncExceptionfails the test. - Put the "what comes next" decision in a separate
@TestVisiblemethod and test it directly. - Test later links by calling
executeyourself, and assert by re-querying records.
Exercise
A Queueable job's execute method updates a record and then calls System.enqueueJob(new SecondJob()) with no guard. A test enqueues the job between startTest and stopTest. What happens at stopTest, and how do you fix the code so the test can assert on the record update?
Show answer
At stopTest the first job runs, and its call to System.enqueueJob fails with a System.AsyncException because tests can't chain Queueable jobs. The test fails. Fix it by wrapping the enqueue in if (!Test.isRunningTest()), ideally after moving the "which job is next" decision into a separate @TestVisible method. Then the first job's update completes, and the test can re-query the record and assert on it.
Exercise
Why does the chapter's third test call execute(null) on a ChainedAccountJob instead of enqueueing it, and when would passing null be unsafe?
Show answer
The test wants to check what a later link does, and enqueueing it would only run it as another first job, which adds nothing. Calling execute directly is a plain synchronous call, so the test can assert right away. Passing null is unsafe when execute reads the QueueableContext, for example context.getJobId(), because that would throw a NullPointerException. In that case, enqueue the job between startTest and stopTest instead.
Exercise
A chain is supposed to stop after the last ID in the list. Which test proves this without running any async code, and what should it assert?
Show answer
Call buildNext (the method that decides the next step) directly on a job whose list holds a single ID, and assert that it returns null with Assert.isNull. This test also needs no startTest/stopTest window, because buildNext is an ordinary synchronous method.