Sub topic 12
Testing Queueable, Batch, and future code
This chapter assumes you can write a basic @IsTest method, use Assert methods, and create test data with @TestSetup. It also assumes you know what a governor limit is. Here you will test code that runs asynchronously: @future methods, Queueable jobs, and Batch Apex.
Why asynchronous code needs special handling
Asynchronous Apex does not run at the point where you call it. The platform places the work in a queue and runs it later, in its own transaction with its own limits. In a test, that would leave your assertions running before the work happens.
Test.startTest() and Test.stopTest() solve this. Any asynchronous job started between the two calls is held until Test.stopTest(). At that point it runs synchronously, and it finishes before the next line of your test executes. After stopTest(), you can query the database and assert on the result.
Testing a Queueable class
A Queueable class implements Queueable and does its work in execute. This one marks accounts as reviewed.
public class AccountReviewJob implements Queueable {
private List<Id> accountIds;
public AccountReviewJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account a : accts) {
a.Description = 'Reviewed';
}
update accts;
}
}
@IsTest
private class AccountReviewJobTest {
@IsTest
static void marksAccountsAsReviewed() {
Account acct = new Account(Name = 'Acme');
insert acct;
Test.startTest();
System.enqueueJob(new AccountReviewJob(new List<Id>{ acct.Id }));
Test.stopTest();
Account saved = [SELECT Description FROM Account WHERE Id = :acct.Id];
Assert.areEqual('Reviewed', saved.Description, 'The job should mark the account as reviewed');
}
}The query must come after Test.stopTest(). The in-memory acct variable is never updated by the job, so you have to re-query to see the change.
Testing a future method
A @future method follows the same pattern. Future methods must be static and void, and they take only primitive arguments or collections of primitives.
public class AccountNotes {
@future
public static void addNote(Id accountId, String note) {
Account a = [SELECT Id FROM Account WHERE Id = :accountId];
a.Description = note;
update a;
}
}
@IsTest
private class AccountNotesTest {
@IsTest
static void futureMethodSavesNote() {
Account acct = new Account(Name = 'Acme');
insert acct;
Test.startTest();
AccountNotes.addNote(acct.Id, 'Called customer');
Test.stopTest();
Account saved = [SELECT Description FROM Account WHERE Id = :acct.Id];
Assert.areEqual('Called customer', saved.Description, 'The future method should save the note');
}
}Testing a Batch class
Batch Apex splits work into chunks. You start it with Database.executeBatch, and inside a test you should keep the data to a single chunk.
public class RatingBatch 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) {
s.put('Rating', 'Warm');
}
update scope;
}
public void finish(Database.BatchableContext bc) {}
}
@IsTest
private class RatingBatchTest {
@IsTest
static void setsRatingOnAllAccounts() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 50; i++) {
accts.add(new Account(Name = 'Batch ' + i));
}
insert accts;
Test.startTest();
Database.executeBatch(new RatingBatch(), 200);
Test.stopTest();
Integer warm = [SELECT COUNT() FROM Account WHERE Rating = 'Warm'];
Assert.areEqual(50, warm, 'Every account should be rated Warm');
}
}Common errors
- Asserting before
stopTest(). The job has not run yet, so the assertion sees the old data. - Checking the in-memory record. Re-query the database after the job runs.
- Large batch test data. A test that calls
executeBatchruns only the first chunk of work. Keep the record count at or below the batch size, as in the example above. - Chaining jobs. If a Queueable enqueues another Queueable, the second job does not run in a test. Test each job on its own.
Exercise
A test enqueues a Queueable job between Test.startTest() and Test.stopTest(), then asserts on a record's field before calling Test.stopTest(). The assertion fails with the old value. Why, and how do you fix it?
Show answer
The job is held until Test.stopTest() and has not run when the assertion executes. Move the query and the Assert call to after Test.stopTest(), and query the record again from the database so you see the saved changes.