Sub topic 14
Testing queueables, chains, and finalizers
This chapter assumes you can write @IsTest classes, understand Test.startTest and Test.stopTest, and know the queueable, chaining, and finalizer patterns from the earlier chapters.
How asynchronous jobs behave in tests
A queueable job normally runs later, in its own transaction. In a test, Apex runs it when Test.stopTest() is called. Everything enqueued between startTest and stopTest finishes before stopTest returns, so the assertions after it can see the job's effects.
Testing a single queueable
Insert the data first, enqueue between the start and stop calls, then query the records again. The job runs in a separate transaction, so the in-memory variables in your test are stale.
@IsTest
private class AccountRatingJobTest {
@IsTest
static void setsRatingToHot() {
Account a = new Account(Name = 'Test Account');
insert a;
Test.startTest();
System.enqueueJob(new AccountRatingJob(new List<Id>{ a.Id }));
Test.stopTest();
Account result = [SELECT Rating FROM Account WHERE Id = :a.Id];
System.assertEquals('Hot', result.Rating);
}
}Testing chains
A test can run only the first job of a chain. If a job running inside a test tries to enqueue a child, the platform throws an exception about the maximum stack depth. That is why the chunking job guards its child enqueue with Test.isRunningTest().
Plan your tests around that rule:
- Test one slice at a time. Pass a list no larger than the chunk size and assert that all of it was processed.
- Test the "more work remains" branch by passing more IDs than one chunk. Assert that the first slice changed and that the guard stopped the chain cleanly.
- Keep the slicing logic in a plain method you can call directly, so you can test it without enqueuing anything.
@IsTest
private class AccountChunkJobTest {
@IsTest
static void processesFirstSliceOnly() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 250; i++) {
accounts.add(new Account(Name = 'Acct ' + i));
}
insert accounts;
List<Id> ids = new List<Id>(new Map<Id, Account>(accounts).keySet());
Test.startTest();
System.enqueueJob(new AccountChunkJob(ids));
Test.stopTest();
Integer processed = [SELECT COUNT() FROM Account WHERE Description = 'Processed'];
System.assertEquals(200, processed, 'Only the first 200 should be processed in a test');
}
}The guard means a test never proves that the second slice runs. Cover that by testing the slice logic separately, or by calling the job's execute method yourself with the remaining IDs.
Testing finalizers
A finalizer runs after its parent job, so it also runs at Test.stopTest(). To exercise the failure path, enqueue a job that throws an unhandled exception and check for the finalizer's side effect. This example uses a Task record as the log entry, because standard objects exist in every org.
public class FailingJob implements Queueable {
public void execute(QueueableContext context) {
System.attachFinalizer(new FailureLogFinalizer());
throw new IllegalArgumentException('Forced failure');
}
}
public class FailureLogFinalizer implements Finalizer {
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
insert new Task(Subject = 'Job failed: ' + ctx.getException().getMessage());
}
}
}
@IsTest
private class FailureLogFinalizerTest {
@IsTest
static void logsFailure() {
Test.startTest();
System.enqueueJob(new FailingJob());
Test.stopTest();
List<Task> logs = [SELECT Subject FROM Task];
System.assertEquals(1, logs.size());
System.assert(logs[0].Subject.contains('Forced failure'));
}
}Run a second test with a job that succeeds and assert that no Task exists. That proves the finalizer ignores the success path.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Asserting before `stopTest` | The job has not run, so the assertion fails | Put assertions after `Test.stopTest()` |
| Reading a stale in-memory record | Old values appear | Re-query by ID |
| Enqueuing a chain without a guard | Stack depth exception in the test | Guard with `Test.isRunningTest()` |
| Asserting on the second slice of a chain | The slice never runs | Test slice logic directly |
Exercise
A test enqueues AccountChunkJob with 450 account IDs between startTest and stopTest. How many accounts does the test see as processed afterwards, and why?
Show answer
200. The job runs once at stopTest and processes one chunk of 200. The Test.isRunningTest() guard stops it from enqueuing a child for the remaining 250, since chaining is restricted in tests.