Sub topic 12
Testing Queueable, Batch, and future code
This chapter covers how to test asynchronous Apex: @future methods, Queueable jobs, and Batch Apex. It assumes you can write a test class with @IsTest methods, use Assert, and create data with @TestSetup. It also assumes you know what Test.startTest and Test.stopTest do to governor limits.
Why asynchronous code needs special handling
Asynchronous Apex runs later, in its own transaction, after the code that requested it has finished. A test method cannot wait for a job in the normal way. If you enqueue a job and assert on its result on the next line, the job has not run, and the assertion fails.
Salesforce solves this inside tests. Work you request between Test.startTest() and Test.stopTest() is held back. When Test.stopTest() runs, the platform executes that work synchronously, in the same test, and waits for it to finish. After stopTest, you can query the database and assert on the results.
This gives two rules:
- Start the asynchronous work after
Test.startTest(). - Assert only after
Test.stopTest().
The async work also gets a fresh set of governor limits, as described in the startTest chapter. The limits for the job are separate from the limits of the code that surrounds it.
The class under test
The examples in this chapter use one small service. It marks accounts as reviewed, and it does so three different ways. Each way is asynchronous, and each one writes to the Description field so a test has something to check.
public class ReviewService {
public static final String MARKER = 'Reviewed';
@future
public static void markReviewedFuture(Set<Id> accountIds) {
List<Account> accts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account a : accts) {
a.Description = MARKER;
}
update accts;
}
public class ReviewJob implements Queueable {
private List<Id> accountIds;
public ReviewJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
List<Account> accts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account a : accts) {
a.Description = MARKER;
}
update accts;
}
}
public class ReviewBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id FROM Account');
}
public void execute(Database.BatchableContext bc, List<SObject> scope) {
for (SObject s : scope) {
((Account) s).Description = MARKER;
}
update scope;
}
public void finish(Database.BatchableContext bc) {}
}
}Testing a future method
A @future method runs in a separate transaction and takes only primitive types or collections of primitives. In a test, call it between startTest and stopTest, then re-query.
@IsTest
private class ReviewServiceFutureTest {
@TestSetup
static void setup() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 5; i++) {
accts.add(new Account(Name = 'Future ' + i));
}
insert accts;
}
@IsTest
static void futureMarksAccounts() {
Map<Id, Account> before = new Map<Id, Account>([SELECT Id FROM Account]);
Test.startTest();
ReviewService.markReviewedFuture(before.keySet());
Test.stopTest();
List<Account> after = [SELECT Id, Description FROM Account];
Assert.areEqual(5, after.size(), 'All five accounts should still exist');
for (Account a : after) {
Assert.areEqual(ReviewService.MARKER, a.Description,
'Future method should set the marker on every account');
}
}
}The variable before is only used to get the IDs. The assertion uses a fresh query because the in-memory records were never updated; the future method changed the database rows, not your variables.
Testing a Queueable job
A Queueable job is a class that implements Queueable. You start it with System.enqueueJob, which returns a job ID. The same startTest/stopTest pattern applies.
@IsTest
private class ReviewServiceQueueableTest {
@TestSetup
static void setup() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 20; i++) {
accts.add(new Account(Name = 'Queue ' + i));
}
insert accts;
}
@IsTest
static void queueableMarksAccounts() {
List<Id> ids = new List<Id>(new Map<Id, Account>([SELECT Id FROM Account]).keySet());
Test.startTest();
Id jobId = System.enqueueJob(new ReviewService.ReviewJob(ids));
Test.stopTest();
Assert.isNotNull(jobId, 'enqueueJob should return a job Id');
Integer marked = [SELECT COUNT() FROM Account WHERE Description = :ReviewService.MARKER];
Assert.areEqual(20, marked, 'Every queued account should be marked');
}
}Checking the job ID is a weak assertion by itself. It shows the job was accepted, not that it did the right work. The count query is the assertion that matters.
Chained jobs
A Queueable job can enqueue another job from its execute method. In a test, the platform runs the first job at stopTest, but it does not run the chained job. Chained jobs are not executed in tests, and trying to run them in a loop produces an error about the stack depth.
For this reason, test each link of a chain on its own. Call execute on the job directly, or enqueue just that job, and assert on what that one job does. If you want to check that a job chains, make the chaining decision a small method you can test without enqueueing anything.
Testing Batch Apex
A batch class implements Database.Batchable. You start it with Database.executeBatch. In a test, the batch runs at stopTest, and there is an important limit: a test can run only one batch execute. That means the scope you pass must fit in a single chunk. If the query returns more records than the batch size, the extra records are not processed in the test, and the platform raises an error.
Keep the test data below the scope size. The default scope is 200 records.
@IsTest
private class ReviewServiceBatchTest {
@TestSetup
static void setup() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 150; i++) {
accts.add(new Account(Name = 'Batch ' + i));
}
insert accts;
}
@IsTest
static void batchMarksAllAccounts() {
Test.startTest();
Id jobId = Database.executeBatch(new ReviewService.ReviewBatch(), 200);
Test.stopTest();
AsyncApexJob job = [
SELECT Status, NumberOfErrors, JobItemsProcessed
FROM AsyncApexJob
WHERE Id = :jobId
];
Assert.areEqual('Completed', job.Status, 'Batch job should complete');
Assert.areEqual(0, job.NumberOfErrors, 'Batch job should have no errors');
Integer marked = [SELECT COUNT() FROM Account WHERE Description = :ReviewService.MARKER];
Assert.areEqual(150, marked, 'All 150 accounts should be marked');
}
}The AsyncApexJob query is useful for batch and Queueable tests. It tells you whether the job finished and whether any records failed. Pair it with a data assertion, because a job can complete without changing the records you care about.
Testing batch methods without running the job
When the data volume is large, or the logic is complicated, you can call the batch methods directly. This does not use the async framework at all, so there is no limit on the number of calls.
@IsTest
static void executeMethodMarksScope() {
List<Account> scope = new List<Account>{
new Account(Name = 'Direct A'),
new Account(Name = 'Direct B')
};
insert scope;
new ReviewService.ReviewBatch().execute(null, scope);
for (Account a : [SELECT Description FROM Account WHERE Id IN :scope]) {
Assert.areEqual(ReviewService.MARKER, a.Description, 'execute should set the marker');
}
}Passing null for the BatchableContext works only if execute never reads it. If your code uses the context, for example to read the job ID, run the batch through Database.executeBatch instead.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Asserting before `Test.stopTest()` | Assertion sees unchanged data | Move all assertions after `stopTest` |
| Enqueueing outside `startTest`/`stopTest` | The job runs later, after the test, or the assertion fails | Put the enqueue call between the two calls |
| Asserting on in-memory records | Old values appear | Re-query the database after `stopTest` |
| More records than one batch scope | Test error or partly processed data | Keep test data at or below the scope size |
| Expecting a chained job to run | Second job never runs | Test each job separately |
| Only checking `jobId` is not null | Test passes when the job does nothing | Assert on the saved data |
What to assert
For asynchronous code, a useful test checks three things:
- The job was accepted. A non-null job ID, or
StatusofCompletedonAsyncApexJob. - The job did not fail.
NumberOfErrorsis zero for a batch. - The database holds the expected end state. This is the main assertion.
Failure messages matter more here than in synchronous tests. When an async test fails, you cannot step through the job, so the message is often your only clue. Say which record set and which field you expected.
Exercise
A test enqueues a Queueable job with System.enqueueJob(...) inside Test.startTest() and Test.stopTest(). Directly after stopTest(), it runs Assert.isNotNull(jobId, 'Job should be queued') and nothing else. The job has a bug and updates no records, yet the test passes. What is wrong with the test, and what should you add?
Show answer
The assertion proves only that the platform accepted the job and returned an ID. It does not check what the job did. After Test.stopTest(), query the records the job should have changed and use Assert.areEqual to check their expected field values or count. Optionally also query AsyncApexJob and assert that Status is Completed and NumberOfErrors is 0.
Exercise
A batch test inserts 450 accounts in @TestSetup and then calls Database.executeBatch(new ReviewService.ReviewBatch(), 200). Why is this a problem, and how can you test the batch logic anyway?
Show answer
A test can run only one batch execute, and 450 records need three chunks of 200. Reduce the test data to 200 records or fewer so the job fits in one scope. To check the logic against larger volumes, call the batch's execute method directly with a list of records, since that does not use the asynchronous framework.