Sub topic 2
Async Jobs Run Synchronously at `stopTest`
Assume you know basic Apex syntax, SObject DML, assertions, and the purpose of future, Queueable, and Batch Apex.
The Test Window
Asynchronous Apex normally runs in a separate transaction. A test cannot assert its changes immediately after queuing the work. Place the operation inside Test.startTest() and Test.stopTest() instead. Salesforce runs asynchronous work queued between those calls when stopTest() executes.
Use this order:
- Create test data before
startTest(). - Queue or call the asynchronous operation inside the test window.
- Call
stopTest(). - Re-query records and assert the results.
Testing `@future` Methods
Call the future method between the two test calls. The method runs at stopTest().
@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 final query is important. The original SObject variable does not automatically contain changes made in another transaction.
Testing Queueable Jobs
Queue a Queueable job inside the window. Capture its job ID if you need to verify that Salesforce accepted it.
Test.startTest();
Id jobId = System.enqueueJob(new DescriptionJob(a.Id));
Test.stopTest();
Assert.isNotNull(jobId);
Assert.areEqual(
'Processed',
[SELECT Description FROM Account WHERE Id = :a.Id].Description
);The job's execute method runs during stopTest(), so assertions belong after it.
Testing Batch Apex
Insert records before the window, then execute the batch inside it. In a test method, Batch Apex runs one execute scope. Keep test data within the selected scope size.
| Async type | Test action | Assert after |
|---|---|---|
| Future | Call the method | `stopTest()` |
| Queueable | Call `System.enqueueJob` | `stopTest()` |
| Batch | Call `Database.executeBatch` | `stopTest()` |
Test.startTest();
Database.executeBatch(new AccountBatch(), 200);
Test.stopTest();
Integer processed = [
SELECT COUNT()
FROM Account
WHERE Description = 'Batch processed'
];
Assert.areEqual(5, processed);Exercise
Why must a test re-query an Account after Test.stopTest()?
Show answer
The asynchronous job updates the record in a separate transaction, so the test must query the database to read the committed result.