Sub topic 14
Testing queueables, chains, and finalizers
This chapter assumes you can write @IsTest classes, create test data, and use Test.startTest() and Test.stopTest(). It also assumes you have read the earlier chapters on queueables, chaining, and finalizers. Here you will see how asynchronous jobs behave inside a test, which parts you can verify directly, and how to structure code so the untestable parts stay small.
How a test runs a queueable
Production queueable jobs run later, in their own transaction. A test method cannot wait for that, so Apex makes a deal with you. Jobs enqueued between Test.startTest() and Test.stopTest() run synchronously when stopTest is called. After stopTest returns, you can query the results.
The test in the spine shows the basic pattern:
@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);
}
}startTest also resets governor limits for the code between the two calls. Set up your data before startTest so setup DML does not use the limits you want to measure.
Common mistakes with the basic pattern
- Enqueuing outside the window. A job enqueued before
startTestor afterstopTestis not run atstopTest. Your assertions then see unchanged data and fail. - Asserting before
stopTest. The job has not run yet, so the data is unchanged. - Reusing stale variables. The
aobject in the test still holds the old field values. Re-query the record, as the example does.
Checking that the job was enqueued and completed
Sometimes you want to assert on the enqueue itself, not on its effects. Two tools help.
Limits.getQueueableJobs() returns how many jobs the current transaction has enqueued. Call it before stopTest:
@IsTest
static void enqueuesExactlyOneJob() {
Account a = new Account(Name = 'Test Account');
insert a;
Test.startTest();
Id jobId = System.enqueueJob(new AccountRatingJob(new List<Id>{ a.Id }));
System.assertEquals(1, Limits.getQueueableJobs());
System.assertNotEquals(null, jobId);
Test.stopTest();
AsyncApexJob job = [
SELECT Status, NumberOfErrors
FROM AsyncApexJob
WHERE Id = :jobId
];
System.assertEquals('Completed', job.Status);
System.assertEquals(0, job.NumberOfErrors);
}The AsyncApexJob query is the same monitoring query you use in production. It is a useful check for a job that has no visible side effect, but an assertion on the data is usually stronger. A job can complete and still do the wrong thing.
Testing chained jobs
The platform does not let a queueable enqueue another queueable while it runs inside a test. If it tries, the second System.enqueueJob throws an exception about the maximum stack depth. This is why the spine's chunking job has the guard:
if (!rest.isEmpty() && !Test.isRunningTest()) {
System.enqueueJob(new AccountChunkJob(rest));
}The guard keeps the test from failing, but it also means your test never exercises the chaining line. You have three ways to deal with that.
- Test one link at a time. Give the job more records than one chunk holds and assert that only the first slice was processed. This proves the slicing logic.
- Move decisions into plain methods. Put the slicing into a static method that returns the current slice and the remainder. Unit-test that method with no queueable involved.
- Accept a small untested line. The
System.enqueueJob(new AccountChunkJob(rest))call is one line. If the slicing is correct and the constructor receives the remainder, the risk is low.
Here is a test for the first approach, using the AccountChunkJob from the chaining chapter:
@IsTest
private class AccountChunkJobTest {
@IsTest
static void processesOnlyFirstSliceInTest() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 250; i++) {
accounts.add(new Account(Name = 'Chunk ' + i));
}
insert accounts;
List<Id> ids = new List<Id>();
for (Account a : accounts) {
ids.add(a.Id);
}
Test.startTest();
System.enqueueJob(new AccountChunkJob(ids));
Test.stopTest();
Integer processed = [
SELECT COUNT() FROM Account WHERE Description = 'Processed'
];
System.assertEquals(200, processed, 'Only one slice runs in a test');
}
}The expected value of 200 is a statement about the test environment, not the production behavior. In production all 250 records end up processed. Say so in the assertion message so the next developer does not read it as a bug.
Testing a finalizer
A finalizer runs after its parent queueable finishes, so in a test it runs at stopTest along with the job. You cannot construct a FinalizerContext yourself, so you cannot call execute(FinalizerContext) directly from a test. You must let the platform run the parent job and then check what the finalizer did.
The success path
When the parent succeeds, ctx.getResult() is ParentJobResult.SUCCESS and the ImportFinalizer from the retry chapter returns without doing anything. To test it, run the job and assert that no retry happened and no failure was logged:
@IsTest
static void successDoesNotRetry() {
Test.startTest();
System.enqueueJob(new ImportJob(new List<Id>(), 1));
Test.stopTest();
Integer jobs = [
SELECT COUNT() FROM AsyncApexJob
WHERE ApexClass.Name = 'ImportJob'
];
System.assertEquals(1, jobs, 'A successful run must not enqueue a retry');
}The failure path
To exercise the failure branch, the parent must throw an unhandled exception. Add a way to force that, such as a constructor flag or a custom record that makes the work fail, and keep it out of the production path. Then run it:
Test.startTest();
System.enqueueJob(new ImportJob(ids, 1));
try {
Test.stopTest();
} catch (Exception e) {
// The parent's unhandled exception can surface here.
}Wrapping stopTest in try/catch is a defensive choice. Whether the exception reaches your test depends on the platform, and the catch makes the test pass either way. The assertions after the block are the real check. Look for a visible effect of the finalizer, such as a log record it inserts, or an extra AsyncApexJob row if it re-enqueued.
Keep the retry decision in a testable method
Because you cannot build a FinalizerContext, move the decision out of execute. Take plain values as parameters:
public class RetryPolicy {
public static Boolean shouldRetry(ParentJobResult result, Integer attempt, Integer maxAttempts) {
return result != ParentJobResult.SUCCESS && attempt < maxAttempts;
}
}The finalizer calls RetryPolicy.shouldRetry(ctx.getResult(), attempt, MAX_ATTEMPTS). Now you can test every combination with no job at all:
@IsTest
private class RetryPolicyTest {
@IsTest
static void retriesOnlyFailuresBelowTheCap() {
System.assertEquals(false, RetryPolicy.shouldRetry(ParentJobResult.SUCCESS, 1, 3));
System.assertEquals(true, RetryPolicy.shouldRetry(ParentJobResult.UNHANDLED_EXCEPTION, 1, 3));
System.assertEquals(true, RetryPolicy.shouldRetry(ParentJobResult.UNHANDLED_EXCEPTION, 2, 3));
System.assertEquals(false, RetryPolicy.shouldRetry(ParentJobResult.UNHANDLED_EXCEPTION, 3, 3));
}
}This test is fast, needs no data, and covers the boundary at the maximum attempt count, which is where retry bugs usually hide.
Testing callouts in a queueable
Tests cannot make real HTTP callouts. If your job implements Database.AllowsCallouts, register a mock before stopTest, because the callout happens when the job runs:
Test.setMock(HttpCalloutMock.class, new MyServiceMock());
Test.startTest();
System.enqueueJob(new SyncJob(ids));
Test.stopTest();If you forget the mock, the test fails with an error that callouts are not supported in tests.
What to test, and how
| Behavior | Technique | What to assert |
|---|---|---|
| Job does its work | Enqueue between `startTest` and `stopTest` | Re-queried record values |
| Job was enqueued once | `Limits.getQueueableJobs()` before `stopTest` | The count |
| Job completed | Query `AsyncApexJob` by the returned ID | `Status`, `NumberOfErrors` |
| Slicing logic | Run one link with more than one slice of data | Only the first slice changed |
| Chain continues | Extract slicing into a static method | The returned slice and remainder |
| Finalizer on success | Run a succeeding job | No retry, no failure record |
| Finalizer on failure | Run a job forced to throw | Log record or extra job row |
| Retry cap | Test the policy method directly | Result at each attempt number |
| Callouts | `Test.setMock` before `stopTest` | Data written from the mocked response |
Edge cases to remember
- Statics are not a dependable way to pass results out of a job. Prefer data you can query.
- Bulk-test your jobs with more than 200 records. A job that works on three records can fail on 201 because of query or DML limits.
- A queueable that runs fine in a test can still fail in production because of mixed DML, record locks, or real callout behavior. Tests reduce risk but do not remove it.
Exercise
A developer writes a test for AccountChunkJob with 250 accounts and asserts that all 250 have Description = 'Processed' after Test.stopTest(). The test fails with only 200 processed. Is the job broken, and how should the test be fixed?
Show answer
The job is not broken. Chaining is not allowed in a test, so the Test.isRunningTest() guard stops the second job from being enqueued, and only the first slice of 200 runs. Fix the test to assert 200 processed (and document why), and cover the slicing logic for the remainder by moving it into a static method that you unit-test directly.
Exercise
Why can't you test a finalizer's failure branch by calling its execute method directly, and what design change makes the decision testable?
Show answer
You cannot create a FinalizerContext in a test, so you cannot pass one to execute. Move the decision into a plain method that takes values such as ParentJobResult, the attempt number, and the maximum, like RetryPolicy.shouldRetry. Test that method directly for each result and attempt count, and add a smaller end-to-end test that runs a forced-failure job and checks for the finalizer's visible effect.