Sub topic 5
Async jobs run synchronously at stopTest
This chapter assumes you can write a basic @IsTest class, use DML in Apex, and know what @future, Queueable, Batch and Schedulable Apex do. Here you will learn what happens at Test.stopTest() and how to use it to assert on async results.
The problem: async work runs later
In production, an async job runs in its own transaction after the calling transaction commits. A test method is one transaction, and it ends when the method returns. If the test waited for the job normally, the assertions would run before the job did.
Test.stopTest() solves this. Async work queued between Test.startTest() and Test.stopTest() does not run when you queue it. Apex holds it until stopTest() is called. At that point the platform runs all of it synchronously, and the test continues only after the work has finished.
What happens at each step
The sequence is:
- Insert test data before
startTest(). - Call
Test.startTest(). - Run the code under test. Any
@futurecall,System.enqueueJob,Database.executeBatchorSystem.scheduleis held. - Call
Test.stopTest(). The held jobs run, one after another, in the same test method. - Re-query the records and assert.
A worked example
This @future method and its test are the pattern the rest of the tutorial reuses.
public class AccountService {
@future
public static void markReviewed(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Description = 'Reviewed';
}
update accounts;
}
}
@IsTest
private class AccountServiceTest {
@IsTest
static void markReviewedUpdatesDescription() {
Account a = new Account(Name = 'Test Account');
insert a;
Test.startTest();
AccountService.markReviewed(new Set<Id>{ a.Id });
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Reviewed', result.Description);
}
}The call to markReviewed returns immediately, and the account has not changed yet. The change happens when Test.stopTest() runs. The query after stopTest() therefore sees Reviewed.
Re-query, do not reuse the variable
The in-memory variable a still holds the values from before the job ran. The job updated the database row, not your object. Always query the record again after stopTest(), as the example does with result. Asserting on a.Description would see the old value (null) and fail.
Where assertions go
An assertion placed before stopTest() checks the state before the job ran. That is useful in one case: to prove the job has not yet run.
@IsTest
static void jobHasNotRunBeforeStopTest() {
Account a = new Account(Name = 'Timing Test');
insert a;
Test.startTest();
AccountService.markReviewed(new Set<Id>{ a.Id });
Account before = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.isNull(before.Description);
Test.stopTest();
Account after = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Reviewed', after.Description);
}Put this method inside the AccountServiceTest class above. For checking the job's effects, assert after stopTest().
Common mistakes
| Mistake | Result |
|---|---|
| Asserting before `stopTest()` | You see the data from before the job ran, so the test fails. |
| Queuing the job before `startTest()` | The job is not held in the window and may not finish before your assertions. |
| Asserting on the variable you inserted | You see stale values because the object is not refreshed. |
| Forgetting `stopTest()` | Held jobs never run, and your assertions fail. |
Exercise
Exercise
A test inserts an Account, calls Test.startTest(), calls a @future method that sets the Account's Description, calls Test.stopTest(), and then asserts on the Description of the original in-memory Account variable. The assertion fails even though the future method worked. Why, and how do you fix it?
Show answer
The future method updated the database row, not the in-memory object, so the variable still holds the old value. Fix it by querying the Account again after Test.stopTest() (for example, SELECT Description FROM Account WHERE Id = :a.Id) and asserting on the queried record.