Sub topic 7
Testing Queueable jobs
This chapter assumes you can write a basic @IsTest class, do DML on SObjects, and know what a Queueable class does. It also assumes you know that Test.startTest and Test.stopTest mark a test window. Here you will test a Queueable job, check its result, pass state into it, and avoid the common mistakes.
What a Queueable job needs from a test
A Queueable job is a class that implements Queueable and has an execute(QueueableContext) method. You start it with System.enqueueJob. In production the job runs later, in its own transaction. A test method cannot wait for that, so a plain enqueueJob call followed by an assertion would check the record before the job has run.
The test window fixes this. Any Queueable job enqueued between Test.startTest() and Test.stopTest() runs synchronously when stopTest is reached. After stopTest returns, the job is finished and its changes are in the database for that test.
The job under test
This job sets a description on one account. It keeps the account Id in a private field that the constructor fills.
public class DescriptionJob implements Queueable {
private Id accountId;
public DescriptionJob(Id accountId) {
this.accountId = accountId;
}
public void execute(QueueableContext context) {
update new Account(Id = accountId, Description = 'Processed');
}
}The test
@IsTest
private class DescriptionJobTest {
@IsTest
static void jobUpdatesAccount() {
Account a = new Account(Name = 'Queue Test');
insert a;
Test.startTest();
Id jobId = System.enqueueJob(new DescriptionJob(a.Id));
Test.stopTest();
Assert.isNotNull(jobId);
Assert.areEqual('Processed', [SELECT Description FROM Account WHERE Id = :a.Id].Description);
}
}The test has three parts, and each part has a fixed place.
- Setup before
startTest. The account is inserted first. Setup DML counts against the limits of the test's own transaction, so keeping it outside the window leaves the window's limits free for the code under test. - The code under test inside the window. Only
System.enqueueJobsits betweenstartTestandstopTest. - Assertions after
stopTest. The job has run by then. The test re-queries the account, because theavariable in memory still holds the old values.
System.enqueueJob returns the Id of the job. In a test this Id is not useful for much more than a null check. It proves the platform accepted the job. It does not prove the job did its work, so the record assertion is the one that matters.
Why re-querying matters
The job changes the database row. The Account object in the test's local variable is a separate copy in memory, and the job never touches it. If you assert on a.Description, you read the stale copy and the assertion fails, even though the job worked. Always query the record again after stopTest.
// Wrong: reads the in-memory copy, which is still null
Assert.areEqual('Processed', a.Description);
// Right: reads the row the job updated
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Processed', result.Description);Testing a job that is enqueued by other code
Often a trigger or a service class enqueues the job, not the test. The pattern is the same. Put the call that causes the enqueue inside the window, then assert after stopTest.
public class AccountService {
public static void processLater(Id accountId) {
System.enqueueJob(new DescriptionJob(accountId));
}
}
@IsTest
private class AccountServiceQueueTest {
@IsTest
static void processLaterRunsJob() {
Account a = new Account(Name = 'Service Test');
insert a;
Test.startTest();
AccountService.processLater(a.Id);
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Processed', result.Description);
}
}The test does not need to know that a Queueable is involved. It only needs the call to happen between startTest and stopTest.
Checking that a job was queued
Sometimes you want to confirm that a job was enqueued, and you do not want its side effects. The AsyncApexJob object records every async job. Query it after stopTest.
@IsTest
private class JobRecordTest {
@IsTest
static void jobIsRecorded() {
Account a = new Account(Name = 'Record Test');
insert a;
Test.startTest();
Id jobId = System.enqueueJob(new DescriptionJob(a.Id));
Test.stopTest();
AsyncApexJob job = [
SELECT Status, JobType, NumberOfErrors
FROM AsyncApexJob
WHERE Id = :jobId
];
Assert.areEqual('Queueable', job.JobType);
Assert.areEqual('Completed', job.Status);
Assert.areEqual(0, job.NumberOfErrors);
}
}This check is a good second assertion because it catches a job that failed. A job that throws an unhandled exception ends with errors, and NumberOfErrors shows it.
Passing state into the job
A Queueable job can hold any state you give it through its constructor. The state can be a collection, an SObject, or your own class. This is the main advantage over @future, which accepts only primitive types and collections of them.
A job that takes a list of Ids follows the same test pattern.
public class BulkDescriptionJob implements Queueable {
private List<Id> accountIds;
public BulkDescriptionJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> toUpdate = new List<Account>();
for (Id accId : accountIds) {
toUpdate.add(new Account(Id = accId, Description = 'Bulk processed'));
}
update toUpdate;
}
}
@IsTest
private class BulkDescriptionJobTest {
@IsTest
static void jobUpdatesEveryAccount() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 50; i++) {
accounts.add(new Account(Name = 'Bulk ' + i));
}
insert accounts;
List<Id> ids = new List<Id>();
for (Account acc : accounts) {
ids.add(acc.Id);
}
Test.startTest();
System.enqueueJob(new BulkDescriptionJob(ids));
Test.stopTest();
Integer updated = [SELECT COUNT() FROM Account WHERE Description = 'Bulk processed'];
Assert.areEqual(50, updated);
}
}Using 50 records instead of one tests that the job works on a list. A job that only works for one record is a common bug.
Fresh limits in the window
The code between startTest and stopTest gets a fresh set of governor limits. The job that runs at stopTest also has the limits of an async transaction, which are higher than the synchronous ones for some resources, such as heap size and SOQL queries. The setup DML before the window does not use up the window's limits. This means that a test that inserts 150 records in setup can still run a job that does its own DML without hitting the DML row limit.
Testing chained jobs
A Queueable job can enqueue another job from its own execute method. This is called chaining. In a test, the chain does not run all the way through. Salesforce lets the first job run at stopTest, and the call to System.enqueueJob from inside that job is not run in the test context. In older API versions this call threw an exception. In current versions it is silently skipped unless you guard against it.
The safe approach is to test each job on its own and to guard the chaining call.
public class FirstJob implements Queueable {
public void execute(QueueableContext context) {
update new Account(Id = [SELECT Id FROM Account LIMIT 1].Id, Description = 'First done');
if (!Test.isRunningTest()) {
System.enqueueJob(new DescriptionJob([SELECT Id FROM Account LIMIT 1].Id));
}
}
}Using Test.isRunningTest() puts test-only logic into production code, so use it sparingly. A cleaner design keeps the work of each job in a method that the test can call directly. Then the test checks the first job through the window, and checks the second job by enqueuing it separately.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Asserting before `stopTest` | The job has not run, so the assertion fails | Move assertions after `stopTest` |
| Asserting on the in-memory record | The variable still has the old values | Query the record again |
| Setup DML inside the window | Setup uses the window's fresh limits | Do setup before `startTest` |
| Calling `startTest` twice | The test throws an exception | Use one pair per test method |
| Expecting the whole chain to run | Only the first job runs | Test each job on its own |
| Real callout in the job | The test fails with a callout error | Use `Test.setMock` with an `HttpCalloutMock` |
Summary of the pattern
- Insert test data.
- Call
Test.startTest(). - Enqueue the job, directly or through the code that enqueues it.
- Call
Test.stopTest(). - Re-query records and assert on them. Optionally check
AsyncApexJobfor status and errors.
Exercise
A test inserts an Account, calls Test.startTest(), enqueues a Queueable that sets Description to 'Processed', calls Test.stopTest(), and then asserts Assert.areEqual('Processed', a.Description) using the original a variable. The assertion fails although the job worked. Why, and how do you fix it?
Show answer
The job updated the database row, but the variable a is a separate in-memory copy that still has the old value. Query the record again after stopTest, for example [SELECT Description FROM Account WHERE Id = :a.Id].Description, and assert on that value.
Exercise
Where should the test insert its Account records, and why?
Show answer
Before Test.startTest(). The window then gives the code under test a fresh set of governor limits, and the setup DML does not use them up.