Sub topic 11
Testing async Apex with Test.startTest and Test.stopTest
This chapter assumes you can write a basic Apex test class with @IsTest, insert test data, and use Assert methods. It also assumes you have read the earlier chapters on @future, Queueable, Batch, and Scheduled Apex. The examples reuse the classes from those chapters.
Why async code needs special test handling
Async Apex does not run at the line that starts it. System.enqueueJob, Database.executeBatch, System.schedule, and a call to a @future method all hand work to the platform and return. In production the work runs later, in a separate transaction.
A test cannot wait for that. If your test enqueues a job and then queries for the result, the job has not run, and the assertion fails. Test.startTest() and Test.stopTest() solve this. Async work started between the two calls is held back, and Test.stopTest() then runs it synchronously and waits for it to finish. After stopTest, the next line of your test can assert on the results.
What startTest and stopTest do
The pair has two effects.
- Fresh governor limits. Code between
startTestandstopTestgets its own set of limits, separate from the setup code before it. Heavy setup, such as inserting hundreds of records, does not eat into the limits of the code under test. - Async execution at
stopTest. Queued jobs run whenstopTestis called. The job runs with the async limits that apply to its type, not the synchronous limits.
Three rules follow from this:
- Put test data setup before
startTest. - Start the async work between the two calls.
- Assert after
stopTest.
A test method can use only one startTest/stopTest pair. Calling stopTest without startTest is an error.
Testing Queueable jobs
The Queueable test from the spine is the simplest pattern:
@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);
}
}The query must come after stopTest. If you move it above, the description is still empty.
Chained jobs
Apex does not let a Queueable job enqueue a child job inside a running test. The platform throws an exception on the second System.enqueueJob. The chunked example from the chaining chapter is therefore safe in a test only if every chunk fits in one job. Choose one of two approaches:
- Test with 100 records or fewer, so
ChunkedUpdateJobnever chains. - Guard the chaining call with
Test.isRunningTest()and test the chunking logic separately.
Neither approach proves the whole chain works end to end. Each job in the chain is a separate unit you can test on its own.
Finalizers
A finalizer attached with System.attachFinalizer runs after its parent job finishes. In a test, that also happens at stopTest. To test a finalizer, you need a parent job that fails on purpose and a way to observe what the finalizer did. Writing a log record from the finalizer, then querying for it after stopTest, works well.
Testing @future methods
A @future method called between startTest and stopTest runs at stopTest. Callouts are the main complication. Tests cannot make real HTTP callouts, so you must register a mock with Test.setMock before the callout runs.
@IsTest
private class PartnerSyncTest {
private class OkMock implements HttpCalloutMock {
public Integer calls = 0;
public HttpResponse respond(HttpRequest req) {
calls++;
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{}');
return res;
}
}
@IsTest
static void sendsAccountNames() {
Account a = new Account(Name = 'Test');
insert a;
OkMock mock = new OkMock();
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
PartnerSync.sendAccountNames(new Set<Id>{ a.Id });
Test.stopTest();
Assert.areEqual(1, mock.calls);
}
}The mock counts its calls, so the test can prove the callout happened even though the future method returns nothing. Because a future method returns void, a counter like this, or a record the method writes, is the only way to check its effect.
Testing Batch Apex
Database.executeBatch between startTest and stopTest runs start, execute, and finish at stopTest. A test can run only one execute call, so the number of records the batch selects must not exceed the scope size. If you insert more records than one scope holds, the extra records are never processed in the test.
The StaleLeadBatch from the batch chapter filters on LastModifiedDate, which a test cannot set to an old date. For a testable example, here is a small batch with a filter that test data can match:
public class ReviewAccountsBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
[SELECT Id, Description FROM Account WHERE Description = null]
);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Description = 'Reviewed';
}
update scope;
}
public void finish(Database.BatchableContext bc) {}
}@IsTest
private class ReviewAccountsBatchTest {
@IsTest
static void reviewsAllAccountsInOneScope() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 3; i++) {
accts.add(new Account(Name = 'Acct ' + i));
}
insert accts;
Test.startTest();
Id batchId = Database.executeBatch(new ReviewAccountsBatch(), 200);
Test.stopTest();
Assert.areEqual(
3,
[SELECT COUNT() FROM Account WHERE Description = 'Reviewed']
);
AsyncApexJob job = [
SELECT Status, NumberOfErrors FROM AsyncApexJob WHERE Id = :batchId
];
Assert.areEqual('Completed', job.Status);
Assert.areEqual(0, job.NumberOfErrors);
}
}This test checks both the data change and the job record. Checking AsyncApexJob catches the case where the batch ran but had errors.
If your batch class is Database.Stateful, remember that the state is visible only inside the job. To assert on a counter, have finish write it to a record, then query that record after stopTest.
Testing Scheduled Apex
A Schedulable class is hard to test by waiting for the clock. Instead, call System.schedule between startTest and stopTest. Then check the CronTrigger record, which represents the schedule itself.
@IsTest
private class NightlyStaleLeadJobTest {
@IsTest
static void schedulesNightlyRun() {
Test.startTest();
Id triggerId = System.schedule(
'Test nightly stale lead cleanup',
'0 0 2 * * ?',
new NightlyStaleLeadJob()
);
CronTrigger ct = [
SELECT CronExpression, TimesTriggered, NextFireTime
FROM CronTrigger
WHERE Id = :triggerId
];
Assert.areEqual('0 0 2 * * ?', ct.CronExpression);
Assert.areEqual(0, ct.TimesTriggered);
Assert.isNotNull(ct.NextFireTime);
Test.stopTest();
}
}This test proves the class can be scheduled and that the cron expression is the one you meant. It does not prove the batch logic works. Test that in the batch's own test class, as shown above. Keeping the scheduler thin, as the combining chapter recommends, is what makes this split possible.
Testing triggers and other callers of async code
Async calls often start from a trigger or a service class, not from the test itself. The same rule applies: the DML or method call that leads to the async work must happen between startTest and stopTest. If you insert the records in setup, the async work still starts, but it can run at an unexpected point and make assertions confusing. When the code under test is a trigger, put the triggering DML inside the pair.
Common test mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Asserting before `stopTest` | The result looks unchanged | Move assertions after `stopTest` |
| No `Test.setMock` for a callout | "Methods defined as TestMethod do not support Web service callouts" | Register a mock before the async code runs |
| More records than the batch scope size | Some records are not processed | Insert at most one scope of records |
| Chaining a Queueable inside a test | Exception on the child `enqueueJob` | Keep to one job, or guard with `Test.isRunningTest()` |
| Checking only the data, not `AsyncApexJob` | A failed job goes unnoticed | Also assert `Status` and `NumberOfErrors` |
| Using `startTest` twice | Test fails with a start/stop error | Use one pair per test method |
Exercise
A test inserts an Account, calls System.enqueueJob(new AccountReviewJob(...)), then calls Test.startTest(), Test.stopTest(), and queries the Account. The assertion that Description equals 'Reviewed' fails. What is the most likely cause and the fix?
Show answer
The enqueueJob call happened before Test.startTest(), outside the pair, so the test does not control when the job runs. Move the System.enqueueJob call between Test.startTest() and Test.stopTest(). The job then runs at stopTest, and the query after it sees the updated value.
Exercise
You test ReviewAccountsBatch with 250 inserted Accounts and a scope size of 200. After stopTest, only 200 Accounts have Description 'Reviewed'. Why, and how do you fix the test?
Show answer
A test can run only one execute call, so only the first scope of 200 records is processed. Insert 200 records or fewer, or lower the number of records so they fit in one scope. Test multi-scope behavior by reasoning about execute on a single scope, since the test platform will not run a second one.
Exercise
A @future method makes an HTTP callout and returns void. How can a test confirm the callout happened?
Show answer
Register an HttpCalloutMock with Test.setMock before Test.startTest(). Have the mock count its calls or record the request. Call the future method between startTest and stopTest, then assert on the mock's counter after stopTest.