Sub topic 1
Why Asynchronous Apex Is Hard to Test
Prerequisites
This chapter assumes basic Apex syntax, SObject DML, @IsTest classes, assertions, governor limits, and the purpose of future methods, Queueable, Batch, and Schedulable Apex.
Why asynchronous Apex is hard to test
Asynchronous Apex runs later, often in a separate transaction. A future method, Queueable job, or batch job may not finish before the test method reaches its assertion. If the test queries too soon, it sees the old data.
Test.startTest() and Test.stopTest() create a controlled test window. Asynchronous work queued inside that window runs when the test reaches Test.stopTest().
Set up data before the test window
Create records and other test fixtures before Test.startTest(). This keeps setup limits separate from the limits used by the code under test.
The test should use its own data. Salesforce tests normally run with SeeAllData=false, so records from the organization are unavailable unless the test creates them.
How Test.startTest and Test.stopTest work
Call Test.startTest() once in a test method. Place the operation being tested between it and Test.stopTest(). The code queued in that window runs synchronously when Test.stopTest() executes.
public class AccountService {
@future
public static void markReviewed(Set<Id> accountIds) {
List<Account> accounts = [
SELECT Id FROM Account WHERE Id IN :accountIds
];
for (Account account : accounts) {
account.Description = 'Reviewed';
}
update accounts;
}
}
@IsTest
private class AccountServiceTest {
@IsTest
static void marksAccountReviewed() {
Account account = new Account(Name = 'Test Account');
insert account;
Test.startTest();
AccountService.markReviewed(new Set<Id>{ account.Id });
Test.stopTest();
Account result = [
SELECT Description FROM Account WHERE Id = :account.Id
];
Assert.areEqual('Reviewed', result.Description);
}
}Fresh governor limits between startTest and stopTest
Governor limits restrict resources such as SOQL queries and DML statements. Test.startTest() gives the code under test a fresh set of limits. Setup work before the window does not consume the same limit budget as the tested operation.
Test.stopTest() ends the window and runs queued work. Assert on the final state after it returns.
Exercise
Where should a test query the result of a future method?
Show answer
After Test.stopTest(), because the future method runs when stopTest() is reached.