Sub topic 11
Testing async Apex with Test.startTest and Test.stopTest
This chapter assumes you can write basic Apex unit tests, know SOQL and DML, and have read the earlier chapters on future, Queueable, Batch, and Scheduled Apex.
Why async tests need special handling
Async jobs do not run inline. When code calls System.enqueueJob or Database.executeBatch, the platform queues the job and returns right away. A test that asserts on the result on the next line would find nothing has changed.
Test.startTest() and Test.stopTest() solve this. Async work started between the two calls is held until Test.stopTest(). At that point the platform runs it synchronously and finishes it before the next line executes. Your assertions can then read the final state.
A second benefit: code between startTest and stopTest gets a fresh set of governor limits. Do your test data setup before startTest so it does not use up the limits of the code under test.
Testing a future method
A future method is queued the same way. Call it between the two markers, then assert after stopTest.
Callouts are not allowed in tests, so supply a mock. This example tests the PartnerSync class from the earlier chapter.
@IsTest
private class PartnerSyncTest {
private class OkMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{}');
return res;
}
}
@IsTest
static void sendsAccountNames() {
Account a = new Account(Name = 'Test');
insert a;
Test.setMock(HttpCalloutMock.class, new OkMock());
Test.startTest();
PartnerSync.sendAccountNames(new Set<Id>{ a.Id });
Test.stopTest();
Assert.isNotNull(a.Id);
}
}The method has no database side effect to check, so the test confirms that it runs without throwing.
Testing a Queueable job
Enqueue the job inside the markers, then query the changed records after stopTest.
@IsTest
private class AccountReviewJobTest {
@IsTest
static void marksAccountsReviewed() {
Account a = new Account(Name = 'Test');
insert a;
Test.startTest();
System.enqueueJob(new AccountReviewJob(new List<Account>{ a }));
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Reviewed', result.Description);
}
}In a test, a chained job enqueued from execute does not run. Only the first job runs, so test each job class on its own.
Testing a Batch job
Database.executeBatch inside the markers runs the batch at stopTest. In a test, executeBatch runs only one execute call, so keep test data to at most one scope's worth of records.
@IsTest
private class StaleLeadBatchTest {
@IsTest
static void marksLeadsStale() {
Lead l = new Lead(LastName = 'Old', Company = 'Acme');
insert l;
Test.startTest();
Database.executeBatch(new StaleLeadBatch(), 200);
Test.stopTest();
Lead result = [SELECT Description FROM Lead WHERE Id = :l.Id];
Assert.areEqual(null, result.Description);
}
}LastModifiedDate cannot be set to a past date in a plain insert, so this lead is not old enough to match the query. The assertion confirms that the batch ran and left it alone. To test the matching path, create the record in a way that your org's test utilities support, or move the query filter into a testable method.
Testing Scheduled Apex
Scheduling a job inside the markers does not wait for the cron time. Instead, stopTest runs the scheduled class once.
@IsTest
private class NightlyStaleLeadJobTest {
@IsTest
static void schedulesJob() {
Test.startTest();
Id jobId = System.schedule('Test nightly', '0 0 2 * * ?', new NightlyStaleLeadJob());
Test.stopTest();
CronTrigger ct = [SELECT CronExpression FROM CronTrigger WHERE Id = :jobId];
Assert.areEqual('0 0 2 * * ?', ct.CronExpression);
}
}The assertion checks the CronTrigger record, which proves the schedule was registered.
Summary of behavior
| Job type | Started with | What `stopTest` does |
|---|---|---|
| Future | Method call | Runs the method |
| Queueable | `System.enqueueJob` | Runs the job, but not its chained child |
| Batch | `Database.executeBatch` | Runs one `execute` call and `finish` |
| Scheduled | `System.schedule` | Runs the class once |
Exercise
A test enqueues a Queueable job, asserts on the updated records, and calls Test.stopTest() afterward. The assertion fails. What is wrong and how do you fix it?
Show answer
The job runs only when Test.stopTest() is called, so the assertion runs before the job has executed. Move the assertion after Test.stopTest().
Exercise
Why should you create test records before Test.startTest() instead of inside the markers?
Show answer
Code between the markers gets a fresh set of governor limits. Creating the data before startTest keeps setup from using limits that belong to the code under test.