Sub topic 13
Testing Queueable, Batch and future code
This chapter assumes you can write a basic Apex test class, use Assert methods, and know what Test.startTest and Test.stopTest do. Asynchronous Apex runs later, in a separate transaction. A test has to force that work to finish before it can check the results.
How tests handle asynchronous work
Inside a test, async jobs do not run when you enqueue them. They are held until Test.stopTest() is called. At that point the platform runs them synchronously, and your test can then query the results.
Two rules follow from this:
- Always enqueue the async work between
startTestandstopTest. - Always assert after
stopTest. Before it, the job has not run.
Testing a Queueable
This Queueable marks accounts as reviewed.
public with sharing class AccountReviewJob implements Queueable {
private List<Id> accountIds;
public AccountReviewJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accounts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Description = 'Reviewed';
}
update accounts;
}
}The test enqueues the job, stops the test, and checks the data.
@isTest
private class AccountReviewJobTest {
@isTest
static void marksAccountsAsReviewed() {
Account acc = new Account(Name = 'Acme');
insert acc;
Test.startTest();
System.enqueueJob(new AccountReviewJob(new List<Id>{ acc.Id }));
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :acc.Id];
Assert.areEqual('Reviewed', result.Description, 'The job should mark the account as reviewed');
}
}Testing a future method
A @future method is tested the same way. Call it between startTest and stopTest, then query.
public with sharing class AccountFlagger {
@future
public static void flag(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Rating = 'Warm';
}
update accounts;
}
}
@isTest
private class AccountFlaggerTest {
@isTest
static void setsRatingToWarm() {
Account acc = new Account(Name = 'Acme');
insert acc;
Test.startTest();
AccountFlagger.flag(new Set<Id>{ acc.Id });
Test.stopTest();
Account result = [SELECT Rating FROM Account WHERE Id = :acc.Id];
Assert.areEqual('Warm', result.Rating, 'The future method should set the rating');
}
}Testing a Batch class
A batch class is started with Database.executeBatch. In a test, the scope is limited to one batch of records, which is at most the batch size you pass, up to 200. Keep your test data within that limit. Test one execute call at a time.
public with sharing class StaleAccountBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id FROM Account WHERE Rating = null');
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Rating = 'Cold';
}
update scope;
}
public void finish(Database.BatchableContext bc) {}
}
@isTest
private class StaleAccountBatchTest {
@isTest
static void setsColdRatingOnUnratedAccounts() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 50; i++) {
accounts.add(new Account(Name = 'Acme ' + i));
}
insert accounts;
Test.startTest();
Database.executeBatch(new StaleAccountBatch(), 200);
Test.stopTest();
Integer coldCount = [SELECT COUNT() FROM Account WHERE Rating = 'Cold'];
Assert.areEqual(50, coldCount, 'All unrated accounts should become Cold');
}
}Common mistakes
| Mistake | Result |
|---|---|
| Asserting before `Test.stopTest()` | The job has not run, so the assertion fails or checks old data |
| Enqueuing outside `startTest` and `stopTest` | Enqueueing the job before `startTest` can skip the fresh limits and make the timing unclear |
| Only calling the job without asserting | Coverage rises but nothing is verified |
| Chaining Queueables in a test | The chained job does not run in a test, so test each job on its own |
Exercise
A test enqueues a Queueable, then immediately queries for the changed record and asserts on it, all before calling Test.stopTest(). The assertion fails. Why, and how do you fix it?
Show answer
The Queueable has not run yet, because the platform holds async jobs until Test.stopTest() is called. Put the enqueue call between Test.startTest() and Test.stopTest(), and move the query and assertion after Test.stopTest().